简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM