C++ I/O 流问题:程序要求输入两次或工作不正确

C++ I/O stream issue: program asks for input twice or work incorrectly

我正在尝试编写一个程序,从命令行将输入读取为 int,如果用户输入 int,则程序打印 "Input is " + 如果用户输入的类型不正确,则输出数字"wrong input"。 这是我的代码:

#include <iostream>
#include <string>
using namespace std;

int main() {
 int input;
 cout << "Enter an Int:" << endl;
 cin >> input;

 if (!(cin >> input)) {
  cout << "wrong format input" << endl;
  return 1;
 }

 cout << "input is " << input << endl;
 return 0;
}

现在 cin >> input;(案例 1)程序在输入正确的整数时要求输入 两次;如果用户输入 '2.2' 或 'a'.

,它会打印 "wrong format input"

没有cin >> input;(case-2)程序在输入正确的整数时要求输入一次; 但是当用户输入'2.2'时它打印"input is 2",而不是打印"wrong"信息,程序打印"Input is 2".

我的代码哪一部分有误?我该如何解决这个问题?

对于案例 2:

下面的示例允许在同一行输入多个整数,但不允许输入任何其他内容

#include <iostream>
#include <string>

int main()
{
    std::string input;
    while(std::cin >> input){
        size_t last;
        int res;
        bool good = true;
        try{
            res = std::stoi(input,&last);
        }
        catch(...){
            good = false;
        }
        if(!good || last != input.length()){
            std::cout << "Incorrect input: " << input << ", try again.\n";
        }
        else{
            std::cout << "Integer read: " << res << '\n';
        }
    }
    return 0;
}

/***************
Output
$ ./test
2
Integer read: 2
hello
Incorrect input: hello, try again.
2.2
Incorrect input: 2.2, try again.
1111111111111111111111111111111111111111111111111111111111111111111111
Incorrect input: 1111111111111111111111111111111111111111111111111111111111111111111111, try again.
3 4
Integer read: 3
Integer read: 4
^Z
[3]+  Stopped                 ./test
*/

另一个版本 - 使用 stringstream

    while(std::cin >> input){
        std::istringstream ss(input);
        int res;
        ss >> res;
        if(!ss){
            std::cout << "Incorrect input: " << input << ", try again.\n";
        }
        else{
            char ch = ss.get();//let's check that no more characters left in the string
            if(!ss){
                std::cout << "Integer read: " << res << '\n';
            }
            else{
                std::cout << "Incorrect input: " << input << ", try again.\n";
            }
        }
    }

if(!(cin >> input)) 是第二个输入的原因。只需这样做:

#include <iostream>
#include <string>
using namespace std;

int main() {
 int input;
 cout << "Enter an Int:" << endl;
 cin >> input;

 if (cin.fail()) {
  cout << "wrong format input" << endl;
  return 1;
 }

 cout << "input is " << input << endl;
 return 0;
}