【问题标题】:extract cin data to a variable that fits将 cin 数据提取到适合的变量
【发布时间】:2014-05-17 15:53:49
【问题描述】:

如果输入无效,我想从 cin 中提取无效输入并将其存储在适合的变量中。我怎样才能做到这一点?

#include<iostream>

using namespace std;

int main(){
    int number;
    cout << "Enter a number: " << endl;
    cin >> number;

    if(cin.fail()){
    cout << "Error!" << endl;
    //HOW CAN I STORE THE INVALID INPUT WHICH IS STORED IN cin INTO A STRING?
    }   

return 0;

}

【问题讨论】:

  • 你可以尝试使用字符串变量,使用gets();在cin>>数字之后;如果用户输入任何非数字值,它将转到该字符串。
  • 输入到字符串或字符串流,然后尝试将其解析为数字。

标签: c++ string input error-handling cin


【解决方案1】:

当您检测到设置了failbit 时,将其重置,然后使用std::getline 将整行无效输入从std::cin 读入std::string

#include <iostream>
#include <string>


int main()
{
        int number;

        while(true)
        {
                std::cout << "Enter a number (0 to exit): " << std::endl;
                std::cin >> number;

                if(std::cin.fail())
                {
                        std::string error_data;
                        std::cin.clear(std::cin.rdstate() & ~std::ios::failbit);
                        std::getline(std::cin, error_data);
                        std::cout << "You didn't enter a number - you've entered: " << error_data << std::endl;

                }
                else
                {
                        std::cout << "Number is: " << number << std::endl;
                        if(number == 0)
                        {
                                break;
                        }
                }

        }
        return 0;
}

【讨论】:

    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    • 2011-06-15
    • 2020-07-11
    • 2020-04-27
    • 1970-01-01
    • 2018-08-23
    相关资源
    最近更新 更多