Jer*_* S. 2 c++ cout flush ostream
您好,我正在编写一个简短的程序来实现 shell,但遇到了一个不寻常的问题。由于某种原因,我无法清除 std::cout 缓冲区。该程序不会打印消息。我知道一个简单的解决方案是切换到 std::cerr,但是有没有办法让消息用 cout 打印?我尝试过的事情:
std::cout.flush() std::endl在将任何内容写入标准输出之后插入。std::flush到输出流中std::cout.setf(std::ios::unitbuf);我发现这应该取消缓冲输出。非常感谢任何帮助,这是我的代码:
int main()
{
//Tryed this to unbuffer cout, no luck.
std::cout.setf(std::ios::unitbuf);
std::string input;
//Print out shell prompt and read in input from keyboard.
std::cout << "myshell> ";
std::getline(std::cin, input);
//**********************************************************************
//Step 1) Read in string and parse into tokens.
//**********************************************************************
char * buf = new char[input.length() + 1];
strcpy(buf, input.c_str());
int index = 0;
char * command[256];
command[index] = std::strtok(buf, " "); //Get first token.
std::cout << command[index] << std::endl;
while (command[index] != NULL)
{
++index;
command[index] = std::strtok(NULL," "); //Get remaining tokens.
std::cout << command[index] << std::endl;
}
std::cout.flush(); //No luck here either
//HERE IS WHERE MY PROBLEM IS.
std::cout << index << " items were added to the command array" << std::endl;
delete[] buf;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
问题是你在循环的最后一次迭代中发送NULL到,这会导致 UB ,在你的情况下是 jamming 。在发送任何内容之前检查一下就可以了:coutwhilecoutNULLcout
if (command[index] != NULL) {
std::cout << command[index] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)