Valeria
Valeria

Reputation: 1212

ifstream does not read first line

I am using the code with ifstream that I used ~1 year ago, but now it does not work correctly. Here, I have the following file (so, just a line of integers):

2 4 2 3

I read it while constructing a graph from this file:

graph g = graph("file.txt");

where graph constructor starts with:

#include <iostream>
#include <fstream>
#include <sstream>

using namespace std;

graph::graph(const char *file_name) {
    ifstream infile(file_name);
    string line;
    getline(infile, line);
    cout << line << endl; // first output
    istringstream iss;
    iss.str(line);
    iss >> R >> C >> P >> K;
    iss.clear();

    cout << R << " " << C << " " << P << " " << K; // second output
}

The second output (marked in code), instead of giving me 2 4 2 3, returns random(?) values -1003857504 32689 0 0. If I add the first output to check the contents of line after getline, it is just an empty string "".

All the files (main.cpp where a graph is instantiated, 'graph.cpp' where the graph is implemented and 'file.txt') are located in the same folder.

As I mentioned, this is my old code that worked before, so probably I do not see some obvious mistake which broke it. Thanks for any help.

Upvotes: 0

Views: 196

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

These two locations:

  • where your program's original source code is located
  • where your program's input data is located

are completely unrelated.

Since "file.txt" is a relative path, your program looks for input data in the current working directory during execution. Sometimes that is the same as where the executable is. Sometimes it is not. (Only you can tell what it is, since it depends on how you execute your program.) There is never a connection to the location of the original source file, except possibly by chance.

When the two do not match, you get this problem, because you perform no I/O error checking in your program.

If you checked whether infile is open, I bet you'll find that it is not.

This is particularly evident since the program stopped working after a period of time without any changes to its logic; chances are, the only thing that could have changed is the location of various elements of your solution.

Upvotes: 3

Related Questions