cout << "\nPlease enter x-ordinate: ";
cin >> test;
stringstream ss(test);
ss >> x;
while(ss.fail())
{
ss.str("");
cin.clear();
cin.ignore(256, '\n');
cout << "Please enter integer: \n";
cin >> test;
stringstream ss(test);
ss >> x;
cout << x << ss;
} 嗨,我正在尝试测试用户的输入是否是整数,方法是使用sstream检查它是否可以转换为整数x,但是一旦输入有效的整数,while循环仍然是真的,循环继续进行。阿诺酮能帮上忙吗?
发布于 2016-04-21 11:27:55
没有必要从cin流到string,创建一个istringstream,然后从它流到您的号码:它只为额外类型的错误留出空间,例如"12x"被当作12处理,x被忽略,而不是为用户生成警告/错误消息。
您可以更直接地阅读以下内容:
const char* prompt = "\nPlease enter x-coordinate: ";
while (cout << prompt && !(cin >> x))
{
cin.clear();
cin.ignore(256, '\n');
prompt = "Please enter integer: \n";
}如果不需要更改提示符,可以将其直接放入循环中:
while (cout << "\nPlease enter x-coordinate: " && !(cin >> x))
{
cin.clear();
cin.ignore(256, '\n');
std::out << "Please enter an integer.\n";
}注意:您将看到一些类似于您的第一次尝试,其中对string的读取使用的是getline而不是>>,这可能是一个很好的实践,因为它允许您计数行号(对于解析文件更有用,而不是std::cin),并在其他预期数据旁边出现检查值。看起来是这样的:
std::string line;
while (std::cout << "Enter coordinate:" &&
getline(std::cin, line))
{
std::istringstream iss(line);
if (iss >> x)
break;
std::cout << "Error - invalid coordinate, please enter an integer\n";
}
...use x...发布于 2016-04-21 11:15:00
你的代码有点小问题..。您有两个完全不同的变量,同名,一个在循环条件中使用,一个在循环体内。这两个变量在任何方面都没有关联或联系。
相反,通过设置第一个ss变量的字符串,重用其第一个变量:
...
cin >> test;
ss.str(test);
...您还没有清除循环中的ss流的状态,只清除cin的状态,这就是您的循环从未结束的原因。
我还建议您使用这样的事实:流可以用作布尔条件,并且operator>>函数返回对流的引用,然后可以执行以下操作
cout << "\nPlease enter x-ordinate: ";
getline(cin, test);
istringstream ss(test);
while(!(ss >> x))
{
ss.clear();
cout << "Please enter integer: \n";
getline(cin, test);
ss.str(test);
}见下面是上面的一个例子。
当然,也可以直接使用cin:
int x;
while (!(cin >> x))
{
cin.clear();
cin.ignore(numeric_limits<std::streamsize>::max(), '\n');
cout << "Please enter integer: \n";
}见下面是上面的一个例子。
发布于 2016-04-21 11:15:40
测试变量是什么类型?一根绳子?您可以尝试使用一个字符串作为输入的通用解析器:
template<class T>
bool tryparse(const string word, T& res)
{
istringstream parser(word);
bool status = (parser >> res);
return status;
}https://stackoverflow.com/questions/36767773
复制相似问题