我正在尝试构建一个简单的代码,在您输入了一些方向输入后,该代码可以在二维中给出坐标。问题是我不知道当用户按下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;
忽略空格以及空行。这里的字符串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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句