简体   繁体   English

将缓冲区与char比较不起作用

[英]Comparing a buffer with a char does not work

I'm making a function to print a whole line from a .txt file, until the end of the line is reached, however it doesn't seem to work, as it prints out the whole text (And yes, the Sleep() function actually works in the while) 我正在制作一个函数来从.txt文件中打印整行,直到到达该行的末尾,但是它似乎不起作用,因为它会打印出整个文本(是的,Sleep()函数实际上在一段时间内起作用)

void string_push(ifstream& file, string text, int time,int tm){
    char * buffer = new char [1];
    while (*buffer != '\n'){
        file.read(buffer,1);
        cout << *buffer;
        Sleep(tm);
    }
    Sleep(time);
}

I've tried inserting an 'y' at the end of the line, and replacing >'\\n' with >'y', but it still doesn't work. 我尝试在行尾插入'y',然后用>'y'替换>'\\ n',但仍然无法正常工作。 What's wrong with it? 它出什么问题了?

I don't understand why you are creating a array of 1 character from dynamic memory. 我不明白为什么您要从动态内存中创建一个1个字符的数组。 You should use a char variable: 您应该使用char变量:

void string_push(ifstream& file,  
                 string    text,
                 int       time,
                 int       tm)
{
    char b = '\0';
    while (b  != '\n')
    {
        file.read(&b,1);
        cout << b;
        Sleep(tm);
    }
    Sleep(time);
}

By using a temporary char variable, you eliminate memory fragmentation and the problems or memory management (allocation and deallocation). 通过使用临时char变量,可以消除内存碎片和问题或内存管理(分配和释放)。 Also, it eliminates the need to a call to the memory manager, thus making your program more efficient (the process can probably fit a character in a register and not use memory). 而且,它消除了对内存管理器的调用,从而使您的程序更高效(该过程可能将字符放入寄存器中而不使用内存)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM