[英]cout not printing anything to console
I am trying to use cout
to print out c strings from a dynamically allocated 2D char array called charArray
.我正在尝试使用
cout
从名为charArray
的动态分配的二维字符数组中打印出 c 字符串。 The snippet where I am printing is here:我打印的片段在这里:
for(int k=0; k<intSize; k++)
{
std::cout<<"hello"<<std::endl;
std::cout<<charArray[intSize-1-k]<<std::endl;
}
for(int i = 0; i<intSize; i++)
{
delete [] charArray[i];
std::cout<<i<<std::endl;
}
delete [] charArray;
intSize
is how many C strings are in charArray
. intSize
是许多C字符串如何在charArray
。 However, when I run the program, "hello"
is printed once, and nothing else prints, not the charArray
nor the i in the second for loop.但是,当我运行程序时,
"hello"
被打印一次,没有其他打印,不是第二个 for 循环中的charArray
和 i。 I already confirmed earlier in my code that charArray
is properly filled by successfully using cout
.我之前已经在我的代码中确认通过成功使用
cout
正确填充了charArray
。 I ran gdb to try and find the issue, and in gdb the for loops are fully iterating through, so for some reason after the first cout
, the couts stop working.我运行 gdb 来尝试查找问题,并且在 gdb 中 for 循环完全迭代,因此由于某种原因在第一次
cout
, couts 停止工作。 I also tried to flush after every cout
, but still the same thing.我也尝试在每次
cout
后冲洗,但仍然是同样的事情。
Try this:尝试这个:
#include <iostream>
int main()
{
const char*nul = nullptr;
std::cout << "before "<< nul << "after\n";
}
The output will be:输出将是:
before
This is what is happening to you - you are trying to print a nullptr string.这就是发生在您身上的事情 - 您正在尝试打印一个 nullptr 字符串。 One of
charArray[intSize-1-k]
is null. charArray[intSize-1-k]
为空。 Possibly reading it out of bounds.可能会越界阅读它。 Writing a null string sets badbit to
std::cout
.写入空字符串将 badbit 设置为
std::cout
。
To avoid this there are two things you can do:为了避免这种情况,您可以做两件事:
Validate that a char*
is not null, before printing it.在打印之前验证
char*
不为空。
std::cout.exceptions(std::ostream::failbit);
will make operator<<
throw an exception at the offending line of code.将使
operator<<
在有问题的代码行抛出异常。 A debugger can catch the exception, and let you find your bug easily (gdb has catch throw
).调试器可以捕获异常,并让您轻松找到错误(gdb 有
catch throw
)。 If you have an exception handler, don't forget to have it call std::cout.clear();
如果你有一个异常处理程序,不要忘记让它调用
std::cout.clear();
. .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.