0

I was trying to open file and read it using C++. Here's the code:

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

using namespace std;

void open_file(string filename)
{
    string data;
    ifstream file;

    file.open(filename);
    file >> data;
    cout << data;

}

int main()
{
    open_file("file.txt");
}

But the output ends when character in file is space. File:

This message will be printed

Output:

This

Could somebody help me?

2 Answers2

1

Yes. That is the standard behaviour of the extractor.

You should use std::getline to read a complete line. This will read until the end of a line (denoted by '\n').

So:

std::getline(file, data);

Please see here for more information.

A M
  • 14,694
  • 5
  • 19
  • 44
0

Use std::getline()

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

using namespace std;

void open_file(string filename)
{
    string data;
    ifstream file;

    file.open(filename);
    getline(file,data);      //This will read until the end of a line
    cout << data;

}

int main()
{
    open_file("file.txt");
}

Don't use using namespace std , refer to this for more info Why is using namespace std bad?

For more information i recommend getting used to This site

RNGesus.exe
  • 205
  • 1
  • 12