cout c ++中的奇怪行为

 景圣南_863 发布于 2023-02-13 18:50

简介: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];
}

sasha.sochka.. 5

您需要手动刷新流.您应该在发布的代码后使用"cout.flush()".

"std :: cout << std :: endl"的作用是 - 它打印'\n'符号,然后刷新流(与...相同)std::cout.flush().

PS使用"endl"总是一个好习惯是不正确的.您通常应使用'\n'来打印新的线符号.并且std::endl仅在这些情况下使用.

2 个回答
  • 流输出被写入缓冲区,并且在刷新流之前可能无法写入最终目标.std::endl将插入行尾,然后刷新.您可以插入std::flush或调用flush()成员函数进行刷新而不插入行尾,如果这是您想要的.

    始终使用"endl"是一种好习惯

    并不是的.经常刷新,特别是在写入文件时,会降低性能.

    2023-02-13 18:52 回答
  • 您需要手动刷新流.您应该在发布的代码后使用"cout.flush()".

    "std :: cout << std :: endl"的作用是 - 它打印'\n'符号,然后刷新流(与...相同)std::cout.flush().

    PS使用"endl"总是一个好习惯是不正确的.您通常应使用'\n'来打印新的线符号.并且std::endl仅在这些情况下使用.

    2023-02-13 18:52 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有