C++ fileIO 行数
C++ fileIO line count
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
我正在使用此代码读取文件。我需要获取该文件的行数。有没有办法不用第二次读取文件就可以做到这一点?
您已经在字符串中包含内容,因此只需检查该字符串:
size_t count = 0, i = 0, length = str.length();
for(i=0;i<length;i++)
if(str[i]=='\n') count++;
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;
我很想这样做:
auto no_of_lines = std::count(str.begin(), str.end(), '\n');
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
我正在使用此代码读取文件。我需要获取该文件的行数。有没有办法不用第二次读取文件就可以做到这一点?
您已经在字符串中包含内容,因此只需检查该字符串:
size_t count = 0, i = 0, length = str.length();
for(i=0;i<length;i++)
if(str[i]=='\n') count++;
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;
我很想这样做:
auto no_of_lines = std::count(str.begin(), str.end(), '\n');