Reading entire file

4

I'm trying to read a simple file, which contains only two lines, but the program only shows 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")

    
asked by anonymous 29.04.2015 / 20:46

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';
    }
}

Notice that before processing the content a validation is made, 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;
}
    
29.04.2015 / 20:57