2016-11-26 30 views
1
ifstream inFile; 
inFile.open(filename); //open the input file 

stringstream strStream; 
strStream << inFile.rdbuf(); //read the file 

string str = strStream.str(); //str holds the content of the file 

我正在使用此代碼從文件中讀取。我需要獲得該文件的行數。有沒有第二次閱讀文件的方法嗎?C++ fileIO行數

+1

[C++獲取總文件行號(的可能的複製http://stackoverflow.com/questions/19140148/c-get-total -file-line-number) – rbaleksandar

回答

3

你已經有一個字符串的內容,所以只是檢查該字符串:

size_t count = 0, i = 0, length = str.length(); 
for(i=0;i<length;i++) 
    if(str[i]=='\n') count++; 
1

std::count這是algorithm庫可以幫助你。

#include <algorithm> 
#include <iterator> 

//... 

long long lineCount { std::count(
     std::istreambuf_iterator<char>(inFile), 
     std::istreambuf_iterator<char>(), 
     '\n') }; 

std::cout << "Lines: " << lineCount << std::endl; 
+0

不完全正確。 'std :: count'返回'Iterator :: difference_type',在這種情況下,它是'std :: char_traits :: off_type',該類型是實現定義的。我的觀點是,如果你想確保使用正確的返回類型,你應該使用'auto'而不是'long long'。 – Blazo

2

我會想這樣做:

auto no_of_lines = std::count(str.begin(), str.end(), '\n');