Tim M
Tim M

Reputation: 487

getLine() returns newline and no data

I have the following code:

    const char *fn = fileName.c_str();
    std::ifstream file (fn);
    std::vector<std::string> value(20000);
    int i = 0;
    while ( file.good() )
    {
        getline ( file, value[i] );
        i+=1;
        std::cout << value[i]<< std::endl;
        std::cout << i << std::endl;
    }

The program reads the whole file, I know this because the correct number of indexes are printed. However there is no data, just a new line before each printing of "i". This is a file that I have saved from excel in windows and am reading in Linux - Is this my issue? What happened to my data?

Upvotes: 0

Views: 213

Answers (3)

Hiroki
Hiroki

Reputation: 2880

there is no data, just a new line before each printing of "i".

Because you increment i before accessing value[i].

Incrementing i just after accessing value[i] solves the problem of missing data.

DEMO

Upvotes: 2

RealPawPaw
RealPawPaw

Reputation: 986

Edit:

Sorry, I was simply fixing the logic error apparent.

However, here is an ideal version of reading lines of a file:

#include <iostream>
#include <fstream>
#include <vector>

int main() {
    std::ifstream file {"test.txt"};
    std::vector<std::string> values;

    std::string temp;

    while (getline(file, temp)) {
        values.push_back(temp);
    }

    for (int i = 0; i < values.size(); ++i) {
        std::cout << values[i] << '\n' << i << '\n';
    }
}

Upvotes: 0

Thomas Matthews
Thomas Matthews

Reputation: 57749

A better way to read in the file:

std::string text_line;
std::vector<string> file_lines;
while (std::getline(file, text_line))
{
  file_lines.push_back(text_line);
}

Although not optimal speed-wise, it gets the job done and doesn't have an upper limit (except by the amount of memory your program is allowed).

Upvotes: 0

Related Questions