1
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 循环仍然被证明是正确的并且循环继续。任何人都可以帮忙吗?

4

3 回答 3

1

你的代码有一个小问题......你有两个完全不同的变量同名,一个用于循环条件,一个在循环体内。这两个变量没有任何关联或联系。

而是通过设置其字符串重用第一个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-21T11:15:00.683 回答
0

测试变量是什么类型?一个字符串?您可以尝试将字符串作为输入的通用解析器:

template<class T>
bool tryparse(const string word, T& res)
{
   istringstream parser(word);
   bool status = (parser >> res);
   return status;
}
于 2016-04-21T11:15:40.457 回答
0

从流式传输cin到 a string,创建 a istringstream,然后从那里流式传输到您的号码是没有意义的:它只会为额外类型的错误留出空间,例如"12x"被视为12x忽略,而不是为用户生成警告/错误消息。

您可以更直接地阅读如下:

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-21T11:27:55.823 回答