c++ - 无法看到程序的结果,暂停不起作用。请指教

标签 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;

}

有没有办法在最后添加一个暂停,以便我可以看到结果?任何帮助将不胜感激。代码和书上的一模一样。我只是不明白为什么它不起作用。谁能帮忙?

问候

最佳答案

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

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

关于c++ - 无法看到程序的结果,暂停不起作用。请指教,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25516390/

相关文章:

visual-c++ - 不使用 VCRedist_x86.exe 的 Visual C++ Redistributables

c++ - 外部指针在静态库中为空,当不是静态库时工作正常

c++ - 在 Mac OS X 10.9 和 Xcode 上安装 GMP 库

c++ - 包含预处理器指令的多行宏语句

c++ - Bazel:将编译标志添加到默认 C++ 工具链

c++ - Visual 2010 中带有 lambda 函数和枚举的 C2665,是错误还是正常?

c# - 如何在vc++6.0中使用vs2008 [VC++9](托管代码)静态库

c++ - 对整个 vector 应用条件

visual-c++ - Cmake 无法为 Visual Studios 10 amd64 配置项目

c++ - 创建一个像工作区一样的油漆并能够移动它们