简体   繁体   中英

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)

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. What's wrong with it?

I don't understand why you are creating a array of 1 character from dynamic memory. You should use a char variable:

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). 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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