Karol Kondratowicz
Karol Kondratowicz

Reputation: 17

File Reading in C++ including spacebars

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?

Upvotes: 0

Views: 74

Answers (2)

RNGesus.exe
RNGesus.exe

Reputation: 197

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

Upvotes: 0

A M
A M

Reputation: 15277

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.

Upvotes: 1

Related Questions