简介:
在 cout
我期望插入运算符传递的任何值 <<
显示在屏幕上。
通常人们会认为下面的代码可以正常运行:
int n = 0;
cout << n;
确实如此,是的,始终使用 endl
是一种很好的做法.但是我遇到的问题很奇怪(至少对我来说是这样)。
问题: 我有以下代码:
cout << " value at array point 0: " << (list)[length -1] << endl;
cout << " Retry: " << (list)[length - 1];
list
是指向整数数组的 0 索引内存位置的指针。 length
是数组长度。您会想象这段代码可以毫无错误地运行,对吗?错误的。出于某种原因,第二行不会显示 - 我一点也不知道为什么。然后我添加了 endl
到 " Retry: "
结束出于好奇,它奏效了。我不知道为什么,这真的很困扰我。
提前感谢所有帮助!
代码基本概览
// Prototype
void listAdd( int* list, int& length );
int main()
{
/* this program was created for practice with dynamic memmory with arrays.
It should be able to extend the list, destroy it, and pop from it.
*/
int length = 0;
int *list = NULL;
for( int i = 0; i < 5; i ++)
{
listAdd( list, length );
//listDisplay( list, length);
}
cout << " if this has been displayed the program ended correctly." << endl;
return 0;
}
void listAdd(int *list, int &length) {
int* tempList = new int[ length + 1 ];
for( int i = 0; i < length; i ++ )
{
(tempList)[i] = (list)[ i ];
}
cout << " Enter a number: ";
int stored = 0;
cin >> stored;
cout << endl;
if ( list != NULL )
delete[] list;
cout << " Previous adress: " << hex << list << endl;
list = tempList;
cout << " New address: " << hex << list << endl << dec;
length ++;
cout << " Length: " << length << endl;
(list)[length -1] = stored;
cout << " value at array point 0: " << (list)[length -1] << endl;
cout << " Retry: " << (list)[length - 1];
}
最佳答案
流式输出被写入缓冲区,并且在流被刷新之前可能不会被写入最终目的地。 std::endl
将插入行尾,然后刷新。您可以插入 std::flush
,或调用 flush()
成员函数,以在不插入行尾的情况下刷新,如果这是您想要的。
it is good practice to always use "endl"
不是真的。过于频繁地刷新,尤其是在写入文件时,会降低性能。
关于c++ - cout c++ 中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20290200/