C++中如何控制cin到cout的流程
In C++, how to control the flow of cin to cout
想象一个带有交互式提示的控制台程序。
用户的命令在逻辑上用分号分隔。
这是简化的代码。
#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;
}
问题是输入是这样的(注意:这个输入只有一个return键)。
并且用户只是将其复制并粘贴到命令行中,而不是手动输入。
AAAAAAAAAAAAA; BBBBBBBBBB
BBBBBBBBBBBBB;
我程序的输出是:
propmt> AAAAAAAAAAAAA; BBBBBBBBBB
BBBBBBBBBBBBB;
sample output
sample output
sample output
->
但我希望这部分 BBBBBBBBBBBBB;
在我的示例输出之后显示。
应该是这样的:
propmt> AAAAAAAAAAAAA; BBBBBBBBBB
sample output
sample output
sample output
-> BBBBBBBBBBBBB;
然后当用户输入另一个 Enter 键时,程序可以处理整个 B
命令并显示结果。
您误解了发生这种情况的原因:数据没有从cin
流向cout
。如果您 运行 您的程序使用标准输入或标准输出重定向 from/to 文件,您可以清楚地看到这一点。
相反,用户输入的显示是终端(或其他任何)您的程序 运行ning 提供的功能。C++ 标准库不提供控制此行为的功能——您将需要使用第三方库(例如 ncurses 或 Windows 使用的任何东西)来告诉终端不要回显用户输入。
想象一个带有交互式提示的控制台程序。
用户的命令在逻辑上用分号分隔。
这是简化的代码。
#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;
}
问题是输入是这样的(注意:这个输入只有一个return键)。
并且用户只是将其复制并粘贴到命令行中,而不是手动输入。
AAAAAAAAAAAAA; BBBBBBBBBB
BBBBBBBBBBBBB;
我程序的输出是:
propmt> AAAAAAAAAAAAA; BBBBBBBBBB
BBBBBBBBBBBBB;
sample output
sample output
sample output
->
但我希望这部分 BBBBBBBBBBBBB;
在我的示例输出之后显示。
应该是这样的:
propmt> AAAAAAAAAAAAA; BBBBBBBBBB
sample output
sample output
sample output
-> BBBBBBBBBBBBB;
然后当用户输入另一个 Enter 键时,程序可以处理整个 B
命令并显示结果。
您误解了发生这种情况的原因:数据没有从cin
流向cout
。如果您 运行 您的程序使用标准输入或标准输出重定向 from/to 文件,您可以清楚地看到这一点。
相反,用户输入的显示是终端(或其他任何)您的程序 运行ning 提供的功能。C++ 标准库不提供控制此行为的功能——您将需要使用第三方库(例如 ncurses 或 Windows 使用的任何东西)来告诉终端不要回显用户输入。