如何在用户只需按 C++ 中的输入时获取输出

how to get output when user just presses enter in c++

我正在尝试构建一个简单的代码,在您输入一些方向后给出二维坐标。 问题是我不知道如何在用户按下回车键时给出正确的输出。这应该是 (0,0),因为如果用户只是按下回车,这意味着他没有改变坐标。我怎么知道用户是否刚刚按下回车并相应地给出正确的输出?

这是我完成的代码:

#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;
}

您需要做的是在尝试获取输入时用 if 包裹起来,然后如果成功,请检查输入的字符串是否为空。如果它是空的,你就知道用户在没有给出任何其他输入的情况下按下了回车键。在类似于这样的代码中:

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

如果您想知道为什么这样做,google 它在 isocpp.org 的 "C++ super FAQ"。

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