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

时间:2017-04-23 12:30:03

标签: c++

我在不同配置中使用cin.ignore() / cin.clear() / cin.sync(),但只能使用getch()停止我的程序。有什么想法吗?

#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;
}

1 个答案:

答案 0 :(得分:-1)

输入缓冲区中可能有换行符,因此cin.get()会在输入缓冲区中等待换行符。要暂停该程序,您可以添加另一个cin.get()或使用

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

将忽略换行符之前的所有字符。还包括限制#include <limits>