[英]strange behavior in cout c++
簡介:在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];
}
您需要手動刷新流。 您應該在發布代碼后使用“ cout.flush()”。
“ std :: cout << std :: endl”的作用是-打印'\\ n'符號,然后刷新流(與std::cout.flush()
相同std::cout.flush()
。
PS:使用“ endl”始終是一個好習慣是不正確的 。 通常應使用'\\ n'來打印新的線符號。 並僅在此類情況下使用std::endl
。
流的輸出將寫入緩沖區,並且只有在刷新流后才能將其寫入最終目的地。 std::endl
將插入行尾,然后刷新。 您可以插入std::flush
或調用flush()
成員函數進行刷新,而無需插入行尾。
最好始終使用“ endl”
並不是的。 經常刷新(尤其是在寫入文件時)會降低性能。
endl
刷新標准輸出流。 您的輸出可能只是在緩沖區中,等待打印到屏幕上。 行為沒有任何問題(除了您確實有其他期望)。
嘗試使用手動flush
代替endl。 那應該導致相同的行為。
引用cppreference :
在輸出序列os中插入一個結束符,並通過調用os.put(os.widen('\\ n'))和os.flush()對其進行刷新。
因此,輸出僅在緩沖區中。 輸出更多的東西-或顯式沖洗-將導致顯示它。
我同意其他答案,認為不必要地添加std::endl
或更通常比需要的刷新次數更多不是一個好習慣。
如果您在第二個輸出的末尾添加了std::endl
並起作用,那是因為endl
刷新了流緩沖區。 否則,您將等待下一個緩沖區寫入屏幕(並且如果您的程序在此之前退出,則在關閉窗口之前您可能看不到它-它會寫出並幾乎立即關閉程序)。
如果尚未自動清除流,則需要刷新流。
發送換行符(endl)將導致流刷新。
如果您確實要刷新並將光標保持在同一行,請添加cout.flush()
以顯式刷新緩沖的流數據。 例如:
cout << " value at array point 0: " << (list)[length -1] << endl;
cout << " Retry: " << (list)[length - 1];
cout.flush();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.