2015-09-26 38 views
1

我想建立一个简单的代码,给你的方向输入后,在两个方面的坐标。 问题是我不知道如何在用户按下回车键时输出正确的输出。这应该是(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; 
} 

回答

1

操作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; 
0

你需要做的是包装一个if在你试图得到输入,然后如果成功,检查是否输入字符串放在in是空的或不空的。如果它是空的,则知道用户按下了输入而没有给出任何其他输入。在代码,将是这样的:

if(cin >> input) { 
    if(!input.empty()) { 
     // handle input correctly 
    } 
} 

如果你想知道为什么它这样做的方式,在isocpp.org谷歌,在“C++超级FAQ”。

+0

更新了我的代码,但还是不输出(0,0)。为什么? – jonathan9879

+0

我不知道。如果上面的代码是你正在编译的确切代码,那么你在本身中调用main是不正确的,并且会导致堆栈溢出。你将不得不调试你的代码,也许用添加的printf等价物来看看发生了什么。至少,为从cin读取失败并打印的情况添加一个else(以便您可以验证您的代码是否按照您的预期方式执行) – 2015-09-26 22:12:15