[英]Count new lines from file doesn't work properly
我正在嘗試從我的文件中計算新行,但它似乎不起作用。 當有 1 個新行時,它給我結果 0。 我怎樣才能解決這個問題?
getline(file, newstring);
char line;
int lines = 0;
for (int i = 0; i < newstring.length(); i++)
{
if(line== '\n')
{
lines++;
}
}
cout << lines;
據我了解,這也可能提供您需要的東西:
#include <iostream>
#include <algorithm>
#include <fstream>
int main()
{
std::ifstream inFile("file");
// DISPLAY number of `\n` characters
std::cout << std::count(std::istreambuf_iterator<char>(inFile),
std::istreambuf_iterator<char>(), '\n') << std:: endl;
inFile.seekg(0); // reset the inFile stream to the first caracter to be read
/** this also works - thanks to @Armin Montigny for the suggestion*/
// DISPLAY number of `\n` characters
std::cout << std::count(std::istreambuf_iterator<char>(inFile),
{}, '\n');
}
如果我有這樣的文件:
這將計算11
換行符。
std::getline
讀取一整行(並且只有一個;它被稱為“getline”,而不是“getlines”)直到行終止符,但結果不包括該終止符。
您無需查看字符串內部,只需計算std::getline
成功的次數即可。
int lines = 0;
while (getline(file, newstring))
{
lines++;
}
cout << lines;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.