C : 使用 ifstream 和 getline();

新手上路,请多包涵

检查这个程序

ifstream filein("Hey.txt");
filein.getline(line,99);
cout<<line<<endl;
filein.getline(line,99);
cout<<line<<endl;
filein.close();

文件 Hey.txt 中有很多字符。远超1000

但我的问题是为什么我第二次尝试打印行。它没有得到打印?

原文由 Mohamed Ahmed Nabil 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 995
2 个回答

根据 C++ 参考( 此处)getline 设置 ios::fail 时提取了 count-1 个字符。您必须在 getline() 调用之间调用 filein.clear();

原文由 Roman Kutlak 发布,翻译遵循 CC BY-SA 3.0 许可协议

获得一条线的更简单方法是使用提取器运算符 ifstream

     string result;
    //line counter
    int line=1;
    ifstream filein("Hey.txt");
    while(filein >> result)
    {
      //display the line number and the result string of reading the line
      cout << line << result << endl;
      ++line;
    }

但是这里的一个问题是,当该行有空格时它不起作用 ' ' 因为它被认为是 ifstream 中的字段分隔符。如果您想实施这种解决方案,请将您的字段分隔符更改为例如 - / 或您喜欢的任何其他字段分隔符。

如果您知道有多少个空格,您可以通过使用 ifstream 的提取器运算符中的其他变量来吃掉所有的空格。考虑该文件具有名字姓氏的内容。

     //file content is: FirstName LastName
    int line=1;
    ifstream filein("Hey.txt");
    string firstName;
    string lastName;
    while(filein>>firstName>>lastName)
    {
      cout << line << firstName << lastName << endl;
    }

原文由 0xDEADBEEF 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题