[英]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;
但我要这部分
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. 然后,当用户输入另一个Enter键时,程序可以处理整个
B
命令并显示结果。
You misunderstand why this happens: data does not flow from cin
to cout
. 您会误解为什么会这样:数据不会从
cin
流到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 (eg ncurses, or whatever Windows uses) to tell the terminal not to echo user input. 相反,用户输入的显示是程序运行所在的终端 (或任何其他方式)提供的功能。C++标准库不提供控制此行为的功能-您将需要使用第三方库(例如ncurses,或Windows使用的任何内容)告诉终端不要回显用户输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.