Vekta
Vekta

Reputation: 65

Getting input from file troubles C++

I've been trying to read some information in from a .txt file in C++ but it's not all working like I expect. Here is some example code:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    char words[255];
    int value = 0;

    ifstream input_stream("test.txt");

    input_stream >> value;
    input_stream.getline(words, 256);

    cout << value << endl;
    cout << words << endl;
}

And test.txt contains:

1234
WordOne WordTwo

What I expect is for the code to print the two lines contained in the text file, but instead I just get:

 1234

I've been reading about getline and istream but can't seem to find any solutions so any help would be appreciated.

Thanks

Upvotes: 1

Views: 115

Answers (4)

gx_
gx_

Reputation: 4770

Here is a somewhat corrected version of your original code:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    char words[256];                  // was 255
    int value = 0;

    ifstream input_stream("test.txt");

    input_stream >> value;
    input_stream.ignore();            // skip '\n'
    input_stream.getline(words, 256);

    cout << value << endl;
    cout << words << endl;
}

Also, I would advise you to use a string instead of a char[] and use the other getline function.

Upvotes: 0

Captain Giraffe
Captain Giraffe

Reputation: 14705

The problem you are seeing is that the first newline after 1234 is not consumed by input_stream>>(int); so the next getline only reads to the end of that file.

This is a very constructed scenario, commonly found in schoolwork. The more common scenario when reading a textfile is to consider the entire file as linebased text.

In this case the more convenient

string line;
while( std::getline( input_stream, line ) ){

}

is appropriate, and way less error prone.

The textfile would commonly have a predefined format. Perhaps name = value lines, and are parsed as such after the line is read from the file.

Upvotes: 0

kc7zax
kc7zax

Reputation: 413

ifstream's getline method gathers input until one of two options is hit. Either a terminating character or the size passed in is reached. In your case, the newline terminator is encountered before the size is reached.

Use another getline to retrieve the second line of text.

Reference

Upvotes: 0

hmjd
hmjd

Reputation: 122001

The newline character remains in the input stream after the read of the integer:

// Always check result to ensure variables correctly assigned a value.
if (input_stream >> value)
{
}

Then, the call to getline() reads the newline character and stops, producing an empty string. To correct, consume the newline character before calling getline() (options include using getline() or ignore()).

Note there is a version std::getline() that accepts a std::string as its argument to avoid using a fixed sized array of char, which is used incorrectly in the posted code.

Upvotes: 3

Related Questions