2017-09-02 54 views
3

我想创建一个可以正确处理所有输入的输入系统。期望的用户输入是双倍的。当用户输入字符串时,字符串流将失败并处理异常。但是,程序无法处理诸如“3245 2345 5”和“21523i4jf”之类的输入,而不是将它们标记为不正确的输入,而是在字符串的开头注册数字,并将其传递给双数而不引发异常。我应该如何让我的程序正确处理所有用户输入?

while (true) 
{ 
    string user_input; 
    cout << "Your Choice: "; 
    getline (cin, user_input); 
    cout << endl; 

    if (user_input == "quit") 
    { 
     break; 
    } 

    try 
    { 
     double number; 
     stringstream stringstream_input; 

     stringstream_input << user_input; 
     stringstream_input >> number; 

     if (stringstream_input.fail()) 
     { 
      throw 90; 
     } 

     cout << number << endl << endl; 
    } 

    catch (int x) 
    { 
     cout << "Please enter a valid input!" << endl << endl; 
    } 
} 
+1

这可能是你想要什么:https://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip -IT/27004240#27004240 – Galik

回答

1

您可以使用std::stod()来正确处理。

try { 
    number = std::stod(user_input); 
} 
catch(const std::invalid_argument& e) { 
    std::cerr << "Invalid input '" << user_input << "'" << std::endl; 
} 
相关问题