2012-01-22 23 views
0

一個新行我想讀取文本所以我做這個如何知道它在文本

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

檢查'buffer.data()[ptrSeek] =='\ n'' –

+0

不是 '\ n' Windows專用? – M2X

+0

@ M2X:不,它在Unix上是通用的。 Windows使用'\ r \ n'。 – Mat

回答

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