我花了一段时间才弄清楚为什么一些cout输出似乎消失在以太中.罪魁祸首:
std::cout<< "This line shows up just fine" << std::endl;
const char* some_string = a_function_that_returns_null();
if (some_string == 0)
std::cout<< "Let's check the value of some_string: " << some_string << std::endl;
std::cout<< "This line and any cout output afterwards will not show up" << std::endl;
Run Code Online (Sandbox Code Playgroud)
上面代码段的输出将是:
This line shows up just fine
Let's check the value of some_string:
Run Code Online (Sandbox Code Playgroud)
因此将NULL输入cout将禁用所有输出.为什么?以及如何解决它?
这不会一直发生 - 具有相同代码的同事获得所有预期的输出.如果你想知道为什么我不能阻止使用if语句将NULL输入cout:我在大型代码库中工作,并且不知道这会发生在哪里!我所知道的是我从未出现过的cout陈述.
更多信息:
a_function_that_returns_null()实际上是getenv("HOST").我检查了命令行echo $HOST,因为HOST变量是空的.如果我这样做export HOST=(bash风味),输出就在那里.我不知道HOST变量最初包含什么,也不知道getenv在修改HOST变量之前最初返回的内容; 我所知道的(some_string == 0)都是真的.
在下面的代码我用过cout<<(char*)NULL;这一行后,我的程序没有打印到输出屏幕.这是否意味着我已经做了close(1)与cout这里?这里到底发生了什么?这是一个错误吗?请分享你的想法.
#include<iostream>
using namespace std;
void f(){
cout<<"\nfun\n";
}
main(){
cout<<(char*)NULL;
f(); //not getting printed !
cout<<"\nhello\n"; //not getting printed !
cout<<"hii how are you?"; //not getting printed, why??
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了gcc和DevCpp编译器,观察到相同的行为.