无法查看程序的结果,暂停不起作用.请告知

Unable to see result of program, pause not working. Please advise

本文关键字:不起作用 暂停 结果 程序      更新时间:2023-10-16

我正在尝试创建一个程序来计算学生的成绩并给出结果。我在一本名为《加速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;
}

有没有办法在结尾加上一个停顿,这样我就能看到结果?如有任何帮助,我们将不胜感激。代码和书完全一样。我只是不明白为什么它不起作用。有人能帮忙吗?

问候

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

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

您要求用户提供一个文件结尾来结束输入。一旦提供了这个文件结尾,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();

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

正如您已经阅读过的字符串,您可以选择逐行输入。所以你可以每行读一个字符串。这允许您检查是否有空行并退出循环。这种方法的缺点是必须将字符串转换为数字。

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