你好我正在写一个简短的程序来实现一个
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; }问题是你在while循环的最后一次迭代中向cout发送NULL,这导致UB,在你的情况下是干扰cout.在向cout发送任何内容之前检查NULL,你没事:
if (command[index] != NULL) { std::cout << command[index] << std::endl; }
精彩评论