2

So I am trying to read from a file named input_file till it reaches the end. I've tried using while (!input_file.eof()) but it goes on for an infinite loop. I looked around on the forum and tried using while (getline(input_file, line)) but that just returns an empty line. I'm not using both getline() and the >> operator like other questions were. How do I get around this? Here's my code:

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

using namespace std;

// Main program
void CalfFlac(ifstream& input_file) {
  string text;
  string line;
  while (getline(input_file, line)) {
    text += line;
  }
  cout << text << endl;
}

int main() {
  ifstream input_file;
  input_file.open("calfflac.in");

  CalfFlac(input_file);
}

input_file contains a single line Confucius say: Madam, I'm Adam. followed by a carriage return.

Thanks for the help!

PS: I'd prefer if the solution remained simple, as this appears to be a pretty simple problem.

Yu Hao
  • 111,229
  • 40
  • 211
  • 267
kreesh
  • 63
  • 1
  • 10
  • I cannot reproduce the problem that you are describing. Even tried it with various line ending combinations like `crlf`, `lf`, `cr`. What platform are you testing this under? – greatwolf Jul 31 '13 at 01:12
  • Did you check that the file opened successfully? `assert(input_file);` – greatwolf Jul 31 '13 at 01:16
  • It is best not to use "assert" to check files, as they can just as easily fail in release mode! – Neil Kirk Jul 31 '13 at 01:16
  • possible duplicate of [Read whole ASCII file into C++ std::string](http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring) – Jerry Coffin Jul 31 '13 at 01:23

1 Answers1

3

EDIT: Make sure you have the right file name! I tried a bogus file name and it printed a blank line as your describe. I tried your code with a correct file name and it worked for me

In main add this line:

int main() {
  ifstream input_file;
  input_file.open("calfflac.in");

  if(!input_file)
    cout << "File path is wrong!";

  CalfFlac(input_file);
}
donsiuch
  • 293
  • 3
  • 6
  • 17