reading until the end of file in C++

后端 未结 2 1232
Happy的楠姐
Happy的楠姐 2020-12-17 04:19

I\'m trying to read till the end of a file for a phonebook app that im converting from C to C++. When I print the the results from the file i get this:

johnn         


        
2条回答
  •  半阙折子戏
    2020-12-17 04:40

    1. Don't use !eof(). It checks whether the last read failure was due to reaching the end of the file. It does not predict the future.

    2. Don't use malloc in C++. If you do, check the return value for errors!

    3. Don't use operator>> for char *. There's no size check so that's just asking for buffer overflows.

    4. The '\n' check on buffer is useless. operator>> for strings stops at whitespace.

    5. You're blindly strcpying a string of unknown length into temp.home of size 20. That's another buffer overflow.

    6. ... I kind of stopped reading there. If you want to read stuff from a file but stop on eof/error, you can do something like this:

    .

    string a, b, c;
    while (true) {
        if (!(in >> a)) break;
        if (!(in >> b)) break;
        if (!(in >> c)) break;
        do_stuff_with(a, b, c);
    }
    

提交回复
热议问题