c++c++11

How to cout on same line as user input? C++


I was wondering if it is possible to output something on the same line where the user gave its input

int money;
cout << "How much money do you have?" << endl;
cin >> money;
//I want this to appear next to the user input
cout << " $";

I hope that you know what i mean and that you can help :)

Edit: I was just wandering if this is possible but as it seems it's not. Not with the standard c++ at least but thanks to everyone who tried to help anyway


Solution

  • The problem is, that when you read the user's input, the terminal interface reads all the way to when the user press the Enter key, and a newline is printed, i.e. the cursor moves to the next terminal line. And then whatever you print appears on that next line.

    You can't really avoid this in purely platform-independent C++, since it requires manipulating the file descriptor "under the hood" of the input stream:

    (or both). This can be done in a standard way on systems conforming to the POSIX standard(s) - but it's complicated. You can read a bit more about it in this SO answer; but the bottom line is that you should use a library to do this. One of:

    should work for you.

    PS: Sometimes your input is not a terminal but a file and you might also need to check whether that is the case.