Question

my partner wrote a bunch of code for one of my projects in a text editor, when i run the code it works perfectly..... now i have copy and pasted all the code into qt creator, and im having an issue

 stringstream ss;
            string line;
            ifstream myfile;
            myfile.open("Instructors.txt");
            if (myfile.is_open()){
                while (getline(myfile,line)){
                    ss << line << ", ";
                }
                myfile.close();
            }
            else cout << "bad open" << endl;

above is the part fo my code that is having the issue, i can assure you all Instructors.txt is indeed in in the correct file, but everytime our code reaches this point imstead of opening the file i get thrown to the else "bad open" why would this be?

Était-ce utile?

La solution

It's hard to say what it may be without any error code, what you can do is to improve your error message with something more meaningful (for you and for your customers):

else cout << "Error opening file: " << strerror(errno) << endl;

strerror (see reference) function returns a string for a given error code captured in by errno macro.

Otherwise you can do it much more C++ish using exceptions: first enable them for your stream:

myfile.exceptions(ifstream::failbit | ifstream::badbit);

Then catch them, all together is:

try
{
    ifstream myfile("Instructors.txt");
    myfile.exceptions(ifstream::failbit | ifstream::badbit);

    while (getline(myfile, line))
    {
        ss << line << ", ";
    }

    myfile.close();
}
catch (ifstream::failure e)
{
    cout << e.what() << endl;
}

Autres conseils

Try to rewrite file name, may be it contains characters from different encodings.

double check the working directory, chances are it is in the build folder (where the executable gets dropped)

in QtCreator you can fix this by going to projects and selecting run; there you will be able to set the working directory

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top