简体   繁体   English

C ++使用cin.get()暂停该程序

[英]C++ pause this program using cin.get()

I have use cin.ignore() / cin.clear() / cin.sync() in different configuration, but can only stop my program using getch() . 我在不同的配置中使用了cin.ignore() / cin.clear() / cin.sync() ,但是只能使用getch()停止我的程序。 Any ideas? 有任何想法吗?

#include <iostream>
#include <sstream>
#include <vector>
#include <conio.h>


using namespace std;

int main() {
    string line;
    if (!getline(cin, line))
        return 0;
    istringstream stream(line);
    string name;
    stream >> name;
    cout << name;
    stream >> name;
    cout << ' ' << name;
    double points;
    double sum = 0;
    vector <double> sums;
    while (stream >> points) {
        sum += points;
        sums.push_back(points);
    }
    cout << ' ' << sum << endl;
    int persons;
    for (persons = 1; getline(cin, line); ++persons) {
        stream.clear();
        stream.str(line);
        stream >> name;
        cout << name;
        stream >> name;
        cout << ' ' << name;
        sum = 0;
        for (int problem = 0; problem<sums.size(); ++problem) {
            stream >> points;
            sum += points;
            sums[problem] += points;
        }
        cout << ' ' << sum << endl;
    }
    cout << endl;
    for (int problem = 0; problem<sums.size(); ++problem)
        cout << problem + 1 << ' ' << sums[problem] / persons << endl;
    _getch();
    return 0;
}

There might be a newline character in the input buffer, so cin.get() takes that newline character waiting in the input buffer. 输入缓冲区中可能会有换行符,因此cin.get()将在输入缓冲区中等待该换行符。 To pause the program, you can add another cin.get() or use 要暂停程序,您可以添加另一个cin.get()或使用

cin.ignore(numeric_limits<streamsize>::max(), '\n');

which will ignore all characters till the newline. 它将忽略所有字符,直到换行符为止。 Also include limits #include <limits> . 还包括限制#include <limits>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM