Tyler Kelly
Tyler Kelly

Reputation: 574

Reading input from a file with getline

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

Upvotes: 0

Views: 539

Answers (1)

mrflash818
mrflash818

Reputation: 934

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;
}

Upvotes: 1

Related Questions