0

I seem to have a fundamental misunderstanding on file input. I assumed my method would work for a project I am working on, but it simply does not. Here is the code:

#include <iostream>

#include <fstream>

#include <cstring>

using namespace std;

int main(){
   ifstream input;
   char fname[20], lname[20];
   input.open("text.txt");

   input.getline(lname, 20, ',');
   input.getline(fname, 20, ' ');
   cout << lname;
   cout << fname;

}

From a file I have:

Squarepants, Spongebob

and the cout statements do not output anything

What I am doing wrong?

thanks

7
  • Assuming the file actually gets opened (I mean you've provided no details to that end, so maybe it didn't), and that the reads succeed, there is output. Commented Apr 6, 2015 at 23:32
  • Make sure your file is opened successfully. Also, always verify that the read operations are successful. Commented Apr 6, 2015 at 23:32
  • 1
    All you need is input.ignore() after the first getline Commented Apr 6, 2015 at 23:48
  • 1
    @user3470987, You told it to read up to the next space. It's at the beginning. Commented Apr 6, 2015 at 23:59
  • 1
    Either use input.ignore(), or get rid of the third argument in the second call to getline. Commented Apr 7, 2015 at 2:13

1 Answer 1

1

This might be a good pattern to use:

std::string lineOfText;

while(fileAccessor.good()) {
    fileAccessor.getline(lineOfText);
    //
    // do stuff
    // do stuff
    //
    if(fileAccessor.eof()) break;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or, remove the individual good() and eof() checks and just use while(fileAccessor) instead. Streams have an operator bool() that returns false when the stream is in bad, fail or eof state.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.