Why are my cout messages not printed after opening a text file?

I am trying to write a program where I am reading a text file, and then I take each line in a text file and save them in a row vector. I think I can open the text file, but I noticed that after I open the text file, nothing will be executed after this moment. For example, I have a cout statement at the end of my main function, which is displayed when I enter a file name that does not exist. However, if I enter a file name, I do not get any output from the last cout statement. Does anyone know why this is? Thank!

int main()
{
    vector<string>line;
    string fileName = "test.txt";
    ifstream myFile(fileName.c_str());
    int i = 0;
    int count = 0;
    vector<string>lines;
        cout << "test" << endl;



    if (myFile.is_open())
    {
            cout << "test2" << endl;    
            while (!myFile.eof())
            {
                getline(myFile, lines[i],'\n');
                i++;
            }
            myFile.close();

    }
        if (!myFile.is_open())
        {
            cout<< "File not open"<< endl;
        }
        myFile.close();

        cout << "Test3" <<endl;




        return 0;
}

+4
source share
2 answers

this:

string fileName = "test.txt";
ifstream myFile(fileName); // .c_str() not needed - ifstream can take an actual string
vector<string> lines;

string line; // temporary variable for std::getline
while (getline(myFile, line)) {
   lines.push_back(line); // use push_back to add new elements to the vector
}

, , , -, "" , . std::getline - reference-to- string. ; lines[i] i . getline , .

, out-of-bounds vector, lines.at(i) lines[i].

+4

push_back(), . , undefined.

std::ifstream input( "filename.ext" );
std::vector<std::string> lines;
for( std::string line; getline( input, line ); )
{
    lines.push_back(line); 
}
+2

Source: https://habr.com/ru/post/1653246/


All Articles