如何知道它是文本中的新行

how to know it's a new line in a text

本文关键字:新行 文本 何知道      更新时间:2023-10-16

我想读取文本中的所有行,所以我正在进行

int main(){
    fstream fs("test.txt",fstream::in|fstream::ate);
    int length = fs.tellg();
    std::vector<char> buffer(length);
    fs.seekg(0, ios::beg);
    fs.read(buffer.data(), length);
    int newlen= 0;
    int ptrSeek = 0;
    while(buffer.data()[ptrSeek] != 0){
        ptrSeek++;
        newlen++;
        if(ptrSeek == buffer.size()) { break;}
    }
    std::vector<char> temp(newlen,0);
    memcpy(&temp[0],&buffer[ptrSeek-newlen],newlen);
}

test.txt:

this is a test
this is a test

所以当它读它的时候,它读起来就像这个

[t] [h] [i] [s] [ ] [i] [s] [ ] [a] [ ] [t] [e] [s] [t] [ ] [t] [h] [i] [s] [ ] [i] [s] [ ] [a] [ ] [t] [e] [s] [t]

我怎么知道它从下一行开始读?

您可以对照n检查字符是否为换行符。

然而,在您的情况下,我建议您使用高级函数,如std::getline,它一次读取一行,可以节省您手动操作的大量劳动力。

阅读这行的惯用方法是:

int countNewline= 0;
std::ifstream fs("test.txt");
std::string line;
while(std::getline(fs, line))
{
      ++countNewline;
      //a single line is read and it is stored in the variable `line`
      //you can process further `line`
      //example
      size_t lengthOfLine = line.size();
      for(size_t i = 0 ; i < lengthOfLine ; ++i)
          std::cout << std::toupper(line[i]); //convert into uppercase, and print it
      std::endl;
}