[英]Count new lines from file doesn't work properly
I am trying to count new lines from my file, but it doesn't seem to work.我正在尝试从我的文件中计算新行,但它似乎不起作用。 It gives me result 0 when there is 1 new line.
当有 1 个新行时,它给我结果 0。 How can I fix this?
我怎样才能解决这个问题?
getline(file, newstring);
char line;
int lines = 0;
for (int i = 0; i < newstring.length(); i++)
{
if(line== '\n')
{
lines++;
}
}
cout << lines;
As I understand it, this may also provide what you need:据我了解,这也可能提供您需要的东西:
#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');
}
If I have a file like this:如果我有这样的文件:
This would count 11
new lines characters.这将计算
11
换行符。
std::getline
reads an entire line (and only one; it's called "getline", not "getlines") up to the line-terminating character, but the result does not include that terminator. std::getline
读取一整行(并且只有一个;它被称为“getline”,而不是“getlines”)直到行终止符,但结果不包括该终止符。
You don't need to look inside the string, you can just count how many times std::getline
succeeds.您无需查看字符串内部,只需计算
std::getline
成功的次数即可。
int lines = 0;
while (getline(file, newstring))
{
lines++;
}
cout << lines;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.