简体   繁体   English

使用getline从文件读取输入

[英]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 并且cout语句不输出任何内容

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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