Cin loop never terminating

被刻印的时光 ゝ 提交于 2019-12-02 05:03:38
glcoder

You may find answer there How to read until EOF from cin in C++

So you can read cin line by line using getline and parse the resulting lines, like that:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    int a, b;

    std::string line;
    while (std::getline(std::cin, line)) {
        std::stringstream stream(line);

        stream >> a >> b;
        std::cout << "a: " << a << " - b: " << b << std::endl;
    }

    return 0;
}

EDIT: Do not forget to check parsing results and stream state for any failure!

You should always check that you input was successful:

if (std::cin >> TmpVal) {
    // do simething with the read value
}
else {
    // deal with failed input
}

In case of a failure you night want to check eof() inducating that the failure was due to having reached the end of the input.

To deal with errors, have a look at std::istream::clear() and std::istream::ignore().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!