且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用cin实现单行整数类型命令行输入验证?

更新时间:2023-11-28 13:17:52

这是因为使用 cin 获取整数会跳过前导空格,其中包括换行符.没有简单的方法可以解决这个问题.

That's because getting an integer with cin will skip leading whitespace, including a newline. There's no easy way around that.

如果要基于行的输入,则可以将输入值作为 string 来获取,然后解释为:

If you want line-based input, you can get your input value as a string and then interpret that:

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

int main (void) {
    std::string inputLine;
    int answer;
    std::cout << "Enter your answer: ";
    while(1) {
        getline (std::cin, inputLine);
        std::stringstream ss (inputLine);
        if ((ss >> answer))
            if ((answer >= 0) && (answer <= 2))
                break;
        std::cout << "No, please enter a VALID answer: " ;
    }
    std::cout << "You entered " << answer << '\n';
    return 0;
}