![](/img/trans.png)
[英]C++ how to restart the loop if user just presses enter or if the input is invalid?
[英]how to get output when user just presses enter in c++
我正在尝试构建一个简单的代码,在您输入了一些方向输入后,该代码可以在两个维度上给出坐标。 问题是当用户只按Enter时我不知道如何给出正确的输出。 这应该是(0,0),因为如果用户只是按下Enter键,则表示他尚未更改坐标。 我如何知道用户是否刚刚按下Enter键并相应地提供适当的输出?
这是我完成的代码:
#include <iostream>
using namespace std;
int main ()
{
int a = 0, b = 0;
string direction;
if( cin >> direction) {
if( !direction.empty() ) {
// handle input correctly
// Interpret directions
for (int i = 0; i < direction.length(); i++) {
if (direction[i] == 'e') a++;
else if (direction[i] == 's') b++;
else if (direction[i] == 'w') a--;
else if (direction[i] == 'n') b--;
}
}
else if (direction.empty()) cout << "(0,0)" << endl;
}
// Output coordinates
cout << "(" << a << "," << b << ")" << endl;
}
cin >> direction;
操作cin >> direction;
忽略空格以及空行。 这里的字符串direction
不是以空格结尾的空白单词。
可以使用std::getline
读取整行。 该函数从流中读取行,并且还读取空行。
因此,解决方案:
int a = 0, b = 0;
string direction;
getline(cin, direction);
if(!direction.empty()) {
// Interpret directions
for (int i = 0; i < direction.length(); i++) {
if (direction[i] == 'e') a++;
else if (direction[i] == 's') b++;
else if (direction[i] == 'w') a--;
else if (direction[i] == 'n') b--;
}
}
// else is not needed, since here a = 0 and b = 0.
// Output coordinates
cout << "(" << a << "," << b << ")" << endl;
您需要做的是在尝试获取输入的过程中包裹一个if
,然后如果成功,请检查输入的字符串是否为空。 如果为空,则您知道用户按下回车键而不给出其他任何输入。 在代码中将类似于:
if( cin >> input) {
if( !input.empty() ) {
// handle input correctly
}
}
如果您想知道为什么要这样做,请在isocpp.org的“ C ++超级常见问题解答”中对其进行搜索 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.