简介:
在cout我期望通过插入运算符传递的任何值<<将显示在屏幕上.
通常人们会认为以下代码可以正常工作:
int n = 0;
cout << n;
Run Code Online (Sandbox Code Playgroud)
它确实如此,是的,总是使用它是一种好习惯endl.但我遇到的问题非常奇怪(至少对我来说).
问题: 我有以下代码:
cout << " value at array point 0: " << (list)[length -1] << endl;
cout << " Retry: " << (list)[length - 1];
Run Code Online (Sandbox Code Playgroud)
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];
}
Run Code Online (Sandbox Code Playgroud)
您需要手动刷新流.您应该在发布的代码后使用"cout.flush()".
"std :: cout << std :: endl"的作用是 - 它打印'\n'符号,然后刷新流(与...相同)std::cout.flush().
PS使用"endl"总是一个好习惯是不正确的.您通常应使用'\n'来打印新的线符号.并且std::endl仅在这些情况下使用.
流输出被写入缓冲区,并且在刷新流之前可能无法写入最终目标.std::endl将插入行尾,然后刷新.您可以插入std::flush或调用flush()成员函数进行刷新而不插入行尾,如果这是您想要的.
始终使用"endl"是一种好习惯
并不是的.经常刷新,特别是在写入文件时,会降低性能.
| 归档时间: |
|
| 查看次数: |
171 次 |
| 最近记录: |