我想建立一个简单的代码,给你的方向输入后,在两个方面的坐标。 问题是我不知道如何在用户按下回车键时输出正确的输出。这应该是(0,0),因为如果用户只是按下输入,这意味着他没有改变坐标。我怎么知道用户是否刚刚按下输入并相应地输出正确的输出?如何获得输出时,用户只需按下输入在c + +
这是我做的代码:
#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;
}
更新了我的代码,但还是不输出(0,0)。为什么? – jonathan9879
我不知道。如果上面的代码是你正在编译的确切代码,那么你在本身中调用main是不正确的,并且会导致堆栈溢出。你将不得不调试你的代码,也许用添加的printf等价物来看看发生了什么。至少,为从cin读取失败并打印的情况添加一个else(以便您可以验证您的代码是否按照您的预期方式执行) – 2015-09-26 22:12:15