Christophe Christophe - 4 months ago 10
C++ Question

In C++, how to control the flow of cin to cout

Image a console program with a interactive prompt.

A user's command is logically split by semicolon.

Here is the simplified code.

#include <iostream>
#include <string>

using namespace std;

int main() {
bool exit = false;
string line;
string input_str;

do {
cout << "propmt> " << flush;

while (getline(cin, line) && !line.empty()) {
if (!input_str.empty()) {
input_str += " ";
}
input_str += line;

auto size = input_str.find_first_of(';');

// find a semicolon
if (size != string::npos) {
/* some code deal with part of string before semicolon */
cout << "\nsample output\nsample output\nsample output\n" << endl;

input_str.erase(0, size + 1);
if (!input_str.empty()) {
cout << " -> " << flush;
} else {
cout << "propmt> " << flush;
}
}
} // getline loop
} while (!exit);

return 0;
}


The problem is when input is like this (Note: only one return key in this input).

And users just copy and paste it into the command line, not input it by hand.

AAAAAAAAAAAAA; BBBBBBBBBB
BBBBBBBBBBBBB;


My program's output is:

propmt> AAAAAAAAAAAAA; BBBBBBBBBB
BBBBBBBBBBBBB;
sample output
sample output
sample output

->


But I want the this part
BBBBBBBBBBBBB;
showed after my sample output.

It should be like this:

propmt> AAAAAAAAAAAAA; BBBBBBBBBB
sample output
sample output
sample output

-> BBBBBBBBBBBBB;


And then when user input another Enter key, the program could deal with the whole
B
command and show the result.

Answer

You misunderstand why this happens: data does not flow from cin to cout. You can see this clearly if you run your program with standard input or standard output redirected from/to file.

Instead, the display of user input is a feature provided by the terminal (or whatever) your program is running in. The C++ standard library provides no functionality for controlling this behavior — you will instead need to use a third party library (e.g. ncurses, or whatever Windows uses) to tell the terminal not to echo user input.