dimanche 30 avril 2017

Can't read whole file into string

I have a code:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(int argc, char *argv[]) {
    ifstream file;

    do {
        string filename;
        cout << "Input file name:" << endl;
        cin >> filename;
        file.open(filename, ios::in);
    } while (!file.is_open());

    string content(istreambuf_iterator<char>(file),
                   istreambuf_iterator<char>());

    cout << "Content:\n" << content << endl;

    if (file.is_open()) {
        file.close();
    }

    return 0;
}

To read this file content:

 1 -1  0 -3  0
-2  5  0  0  0
 0  0  4  6  4
-4  0  2  7  0
 0  8  0  0 -5

But it outputs 1 only and a new line.
P.S. I am a nobie and just learn C++ by samples. What do I doing wrong?

Aucun commentaire:

Enregistrer un commentaire