【问题标题】:seekg tellg end of lineseekg 告诉行尾
【发布时间】:2023-03-28 15:47:01
【问题描述】:

我必须从外部文本文件中读取行,并且需要某些行的 1. 字符。

是否有一个函数可以告诉我指针在哪一行以及另一个函数可以将指针设置为第 x 行的开头?

我必须跳到当前位置之前和之后的行。

【问题讨论】:

    标签: c++


    【解决方案1】:

    我认为没有这样的功能。您可能必须自己使用 getline() 来实现此功能,或者一次扫描文件中的结束字符 (\n) 一个字符,然后只存储该字符之后的一个字符。

    您可能会发现一个向量(可能是vector<size_t>)有助于存储行开始的偏移量,这样您就可以以基于行的方式跳转到文件中。但是没试过,所以可能不行。

    【讨论】:

      【解决方案2】:

      您可以查看ifstream 以在流中读取文件,然后使用getline() 获取std::string 中的每一行。

      这样做,您可以轻松地遍历线条并抓取您需要的字符。

      这是一个例子(取自here):

      // reading a text file
      #include <iostream>
      #include <fstream>
      #include <string>
      using namespace std;
      
      int main () {
        string line;
        ifstream myfile ("example.txt");
        if (myfile.is_open())
        {
          while (! myfile.eof() )
          {
            getline (myfile,line);
            cout << line << endl; // Here instead of displaying the string
            // you probably want to get the first character, aka. line[0]
          }
          myfile.close();
        }
      
        else cout << "Unable to open file"; 
      
        return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-25
        • 2015-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-13
        相关资源
        最近更新 更多