-2

I am trying to read about 2 lines from a file of text into a std::string in c plus plus. I have looked through several answers and found none that work on my device. Can anyone tell me what I am doing wrong? The method is currently returning a null string, and doesn't correctly open the file or read it at all.

std::string readFile(std::string filename) {
  std::ifstream infile;
  infile.open(filename);
  std::string output;
  if (infile.is_open()) {
    while(infile.good()) {
      infile >> output;
    }
  }
  infile.close();
  return output;
}
llllllllll
  • 15,080
  • 4
  • 23
  • 46
  • What exactly it means when you say 'none that works'? What does it mean to 'correctly open a file'? – SergeyA Feb 23 '18 at 21:24
  • `while(infile.good())` will continue to read until the read has failed once. After that failed read the string will be empty. – Bo Persson Feb 23 '18 at 22:00
  • Possible duplicate of [Read whole ASCII file into C++ std::string](https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring) – Jive Dadson Feb 23 '18 at 23:17

1 Answers1

0

Not sure what file you are trying to open but that's a completely separate problem. The code you've written will open a file if you give it a path to a file that it can open. Check your current working directory and confirm the path is correct.

Even after you solve that problem, you're going to have more problems though.

I expect that you are confused because you are repeatedly overwriting output with this line:

infile >> output;

perhaps you meant to declare output as a std::stringstream

And for me it doesn't return an empty string, it returns the last word of the file. I guess it depends what's in your file.

Wyck
  • 5,985
  • 4
  • 34
  • 44