c++ - 使用 getline 从文件读取输入

标签 c++ file-io getline

我似乎对文件输入有一个根本性的误解。我以为我的方法适用于我正在从事的项目,但事实并非如此。这是代码:

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

}

来 self 的文件:

Squarepants, Spongebob

并且 cout 语句不输出任何内容

我做错了什么?

谢谢

最佳答案

这可能是一个很好的模式:

std::string lineOfText;

while(fileAccessor.good()) {
    fileAccessor.getline(lineOfText);
    //
    // do stuff
    // do stuff
    //
    if(fileAccessor.eof()) break;
}

关于c++ - 使用 getline 从文件读取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29481308/

相关文章:

c++插入空 vector 不能使用大括号

c++ - C++仿函数行为

c++ - ifstream getline 问题(它只读取第一行)

c++ - 我应该使用 OR 运算符返回 const 引用还是仅返回引用

c++ - OpenGL 纹理未显示

C++ 类模板问题

c# - 附加字符串时难以保存模板

c - 为什么写入文件时字符会加倍 (uupp)?

c++ - 在 C++ 中逐行读取文件,跳过一些行

c++ - C++ 中的 getline(isstream, string)