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

时间:2012-01-22 06:56:32

标签: c++ fstream

我想阅读文本中的所有行,所以我正在做这个

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]

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

1 个答案:

答案 0 :(得分:3)

您可以查看\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;
}