在c++中计算文本文件中的文本行数时出现错误
Getting error when counting the number of lines of text in a text file in c++
我试图计算文本文件中的行数,但每次我运行此代码时,我都将1987121509作为行数。你能告诉我如何修改我的代码以获得正确的行数吗?谢谢你。
代码如下:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
int numLine;
ifstream dataFile;
dataFile.open("fileforstring.txt");
if(!dataFile)
{
cout<<"Error opening file.";
}
else
{
cout<<"File opened successfully";
}
while(getline(dataFile,line))
{
++numLine; //increment numLine each time a line is found
}
cout<<"nNo of lines in text file is "<<numLine;
dataFile.close();
return 0;
}
下面是正确的代码(我在问问题后发现)没有正确初始化变量的愚蠢错误。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
int numLine = 0; //didn't set it to zero.
ifstream dataFile;
dataFile.open("fileforstring.txt");
if(!dataFile)
{
cout<<"Error opening file.";
}
else
{
cout<<"File opened successfully";
}
while(getline(dataFile,line))
{
++numLine;
}
cout<<"nNo of lines in text file is "<<numLine;
dataFile.close();
return 0;
}
相关文章:
- 尝试使用 WinBGI 显示文本时出现编译器错误
- ISO 中禁止可变长度数组 C++崇高文本中的错误 3.
- SFML 2.4.2 - 绘制文本时出现分段错误
- C++-从文本文件读取矢量错误
- 在图像上覆盖文本的程序会产生无休止的字符串错误
- c++ 添加具有写入文件错误的文本变量
- 写入文本文件错误,QT
- 收集Visual Studio IntelliSense错误,然后通过脚本将其转储到文本文件中
- 将文本字符串作为常量字符 * 参数传递会导致代码分析器错误
- 用于引发字符串文本C++的编译器错误的宏
- C++文本动画错误 C2397
- 如何将C 编译器错误发送到CMD中的文本文件
- 有时写入文本文件时会出现错误
- QFont 错误地将文本适合特定高度
- 尝试将文本文件加载到动态分配的 2D 数组中时出现'Segmentation fault'错误
- 获取 Poco 返回的错误代码的文本
- 分段错误将文本呈现到开罗上下文
- 从文本文件读取 2D 数组错误
- CMD窗口停止工作,文本文件使用fstream读取错误
- 用mingw编译SDL2,使用崇高的文本2错误