【发布时间】:2016-01-13 17:14:24
【问题描述】:
有人告诉我,除非有必要,否则我应该只在我的代码中使用 cin 或 getline 这两者中的任何一个。
我被告知 Cin 会产生异常错误等(不检查输入类型等)
我知道 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 的错误。
那么,问题 - 我应该为这些数据类型使用什么,或者我可以同时使用这两种数据类型吗?
希望大家能理解我的提问。
【问题讨论】:
-
您可以使用
std::istringstream将string转换为数值。 -
这个错误将通过写
inputReturn(defaultValue);BTW来修复。 -
您可以同时使用这两种方法。尽管
>>运算符会读取您的值直到下一个空格或 EndOfLine 或 eof 或目标的 sizeof/capacity 。是的,当使用cin和>>和 getline 时,不会检查类型。与 getline 的区别在于它总是返回一个字符串。 -
如果你保证你的输入格式正确(数字是你所期望的),那么
cin不会有问题。但根据您对问题的措辞,听起来并非如此。因此,您必须读取字符串,或者使用更好的解析器。 +1inputReturn() -
Mubashir Hanif 和 Les,感谢 cmets(这更像是答案)。完全解决了我的问题。