有人告诉我,除非必要,否则我应该只在代码中使用cin或getline这两个代码中的任何一个。
有人告诉我会产生异常错误,例如(不检查输入类型等)
我知道getline()对于字符串和字符更加灵活,但是数字类型呢?我的意思是,我可以将getline字符串解析为数值,但是没有更安全的路由吗?问题是,对于字符串和数字输入,我应该采用哪种方法?
int inputReturn(int x);
int defaultValue = 0;
int main()
{
//Getting numerical input w/getline()
string input = "";
while(true)
{
cout << "Enter a value: ";
getline(cin, input);
stringstream myStream(input);
system("CLS");
if(myStream >> defaultValue)
{
system("CLS");
break;
}
cout << "Invalid input. Try again!" << endl << endl;
}
inputReturn(input); //Converted to numeric value, but still type of string (Error)
system("CLS");
return 0;
}
int inputReturn(int x)
{
return x*2;
}
在此示例中,我将输入的字符串解析为数字值,然后将该值用作int的参数,并得到int的字符串错误。
因此,问题-这些数据类型应使用什么?
我希望你们能理解我的询问。
最佳答案
getline()
可以用于数值,但不能用于整数或 double 。
在您的情况下,可以使用。
还记得#include <string>
关于c++ - 混合cin >>和getline()-C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33145266/