Reading entire file

Asked

Viewed 314 times

4

I am trying to read a simple file, which contains only two lines, but the program shows only one. The program:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    string str;
    ifstream myfile;
    myfile.open("file.lua");
    myfile >> str;
    cout << str << endl;
    myfile.close();
    return 1;
}

The result is:

print(1)

Process returned 1 (0x1) Execution time : 0.044 s Press any key to continue.

The file contains:

print(1) print("Hello")

1 answer

3


This is the canonical way to read a file sequentially in C++

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

int main() {
    ifstream ifs( "myfile.txt" );
    string line;
    while( getline( ifs, line ) ) {
        cout << line << '\n';
    }
}

Note that before processing the contents a validation is performed, ensuring that we do not pass the end of the file.

Closer to your example, and if you want to read the contents of the file at once to a string, I would:

std::ifstream t("myfile.txt");
std::stringstream buffer;
buffer << t.rdbuf();
....

With your case the problem is just reading the first line. You can try:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    string str, str2;
    ifstream myfile;
    myfile.open("file.lua");
    myfile >> str >> str2;
    cout << str << endl;
    cout << str2 << endl;
    myfile.close();
    return 1;
}
  • With your first example, I was able to do

Browser other questions tagged

You are not signed in. Login or sign up in order to post.