Reading a file in C ++

I cannot understand why my code cannot open and read the file. What am I missing?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main (int argc, char * const argv[]) 
{
    string line;
    ifstream myfile ("input_file_1.txt");
    if (myfile.is_open())
    {
        while (!myfile.eof())
        {
            getline (myfile,line);
            cout << line << endl;
        }
    }
    else
    {
        cout << "Was unable to open the file" << endl;
    }

    return 0;
}

The file "input_file_1.txt" is the same directory as my .cpp file, and it has read permissions. I even gave 777 permissions, and I could not read it.

Can someone tell me what I am doing wrong? I really can't figure it out.

+3
source share
5 answers
  • Try using the full path for the file
  • By default, the executable is used to search for the file, not the source.
+4
source

? IDE? , . - .

+3

, . , .

, , . , , .

+3

:

EOF .
(getline() ) , EOF. . . eof() ( EOF). ( getline()), , 0 ( , undefined). (undefined ) .

    while (!myfile.eof())
    {
        getline (myfile,line);
        cout << line << endl;
    }

, :

    while (getline (myfile,line))
    {
        cout << line << endl;
    }

, getline() . , (, while), , (.. EOF ) , . , ( , ).

+3

, ( cpp), - , , , "bin" -. , .

0

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


All Articles