Search code examples
c++stringfstream

Strings retrieved from files displaying garbage


I have 2 files, easyp.txt and easyn.txt, were easyp.txt stores points, and easyn.txt stores names. I have code that displays the top score and the players name. It was working fine, then I edited some other lines, and upon running again, it spews out rubbish. The codes look like this:

case 1:
        infile.open("easyn.txt", ios::out | ios::app);
        ofile.open("easyp.txt", ios::out | ios::app);
        while (getline(infile, STRINGT) && getline(ofile, STRINGO))
        {
            istringstream buffer(STRINGO);
            buffer >> value;
            if (infile.eof() && ofile.eof()){
                printf("The top player for easy is %s with only %i tries!", STRINGD, value);
                break;
            }
            if (value < best)
            {
                STRINGD = STRINGT;
                best = value;
            }
        }
        infile.close();
        ofile.close();
        _getch();
        break;

(lower number of points is better btw)

When I run the program it outputs random ascii characters as the player name, and 1835884884 as the score.

Yes I am using namespace std

The only other time I have file reading/writing is in the following:

            ofstream myfile;
            myfile.open("easyn.txt", ios::out | ios::app);
            if (myfile.is_open())
            {
                myfile << chName << "\n";
                myfile.close();
            }
            myfile.open("easyp.txt", ios::out | ios::app);
            if (myfile.is_open())
            {
                myfile << iTurns << "\n";
                myfile.close();
            }

Thanks for the help


Solution

  • The main problem with your program is this:

    printf("The top player for easy is %s with only %i tries!", STRINGD, value);
    

    The %s format specifier to printf expects a char *, not a std::string. What you want to do to fix that is replace STRINGD with STRINGD.c_str().

    Passing an argument to a varargs function of another type than the function expects to receive invokes undefined behavior. Exactly what happens depends on your architecture and ABI, so I can't really give a detailed explanation about that without such details, but I don't think that matters much anyway. :)