无法看到程序结果,暂停不工作。请指教

时间:2014-08-26 22:50:20

标签: c++ visual-c++

我正在尝试创建一个计算学生成绩的程序,并为您提供结果。我正在做这个,作为一本名为" Accelerated C ++"的书的任务的一部分。

我目前遇到的问题是我输入中期和期末考试成绩以及作业成绩,似乎计算了最终成绩。然而,在我阅读之前它就关闭了。我尝试使用cin.get()添加暂停;最后,但它没有工作。

#include <iomanip>
#include <ios>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>


using std::cin;             
using std::cout;
using std::endl;
using std::setprecision;
using std::string;
using std::streamsize;
using std::vector;
using std::sort; 


int main()
{
//ask for and read the students name
cout << "Please enter your first name: ";
string name;
cin >> name;
cout << "Hello, " << name << "!" << endl;

//ask for and read the midterm and final grades 

cout << "Please enter your midterm and final exam grades: ";
double midterm, final;
cin >> midterm >> final;

//Ask for their homework grades 

cout << "Enter all your homework grades, "
    "followed by end-of-file: ";

vector<double> homework;
double x;
// Invariant: Homework contains all the homework grades read so far
while (cin >> x)
    homework.push_back(x);

// Check that the student entered some homework grades
typedef vector<double>::size_type vec_sz;
vec_sz size = homework.size();
if (size == 0) {
    cout << endl << "You must enter your grades. "
        "Please try again." << endl;
    return 1;
}

// Sort the grades 
sort(homework.begin(), homework.end());

// Compute the median homework grade
vec_sz mid = size / 2;
double median;
median = size % 2 == 0 ? (homework[mid] + homework[mid - 1]) / 2
    : homework[mid];


// compute and write the final grade
streamsize prec = cout.precision();
cout << "Your final grade is " << setprecision(3)
    << 0.2 * midterm + 0.4 * final + 0.4 * median
    << setprecision(prec) << endl;

cin.get();

return 0;

}

有没有办法在最后添加一个暂停,以便我可以看到结果?任何帮助将不胜感激。代码与本书完全相同。我只是不明白为什么它不起作用。有人可以帮忙吗?

此致

2 个答案:

答案 0 :(得分:1)

在再次使用流之前,必须清除流状态。在cin.get()之前发生的输入操作(即while (cin >> x))继续运行,直到流状态不再处于非故障状态。您需要clear()流状态才能再次使用I / O:

std::cin.clear();
std::cin.get();

答案 1 :(得分:0)

您要求用户输入文件结尾以结束输入。提供此文件结尾后,您的cin流不再接受输入。可能是您找到了另一种结束数据输入循环的方法!

cout << "Enter all your homework grades, "
    "followed by -1 : ";

...
while ((cin >> x) && x>=0)
...
         // the enter after your last number would let get() return, so:  
cin.ignore(std::numeric_limits<streamsize>::max(), '\n');  // clear input until '\n' 
cin.get();

变体,带有基于字符串的输入循环:

如果您知道alr​​ead字符串,您可以选择逐行输入。所以你每行都要读一个字符串。这允许您检查是否有空行并退出循环。这种方法的缺点是你必须将你的字符串转换为数字。

cin.ignore(std::numeric_limits<streamsize>::max(), '\n');  // clear previous '\n' 
cout << "Enter all your homework grades, "
    "followed by an empty line : ";
...
string str; 
while (getline(cin, str) && str!="") 
    homework.push_back(stod(str));  // convert string to double
...  // and end of programme as above