Search code examples
c++coordinatesenter

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


I am trying to build a simple code that gives the coordinates in two dimensions after you put some direction input. The problem is I don't know how to give the proper output when the user just presses enter. This should be (0,0) because if the user just presses enter it means he has not changed the coordinates. How can I know if the user has just pressed enter and give the proper output accordingly?

This is the code I have done:

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

Solution

  • The operation cin >> direction; ignores spaces and also empty lines. Here the string direction is not empty whitespace terminated word.

    It is possible to read entire line using std::getline. This function reads line from stream and also it reads empty lines.

    So, the solution:

    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;