문제

I am trying to count the number of lines in a text file but each time i'm running this code i am getting 1987121509 as the number of lines. Can you please tell me how i can modify my code to get the correct number of lines? Thank you.

Here's the code:

#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;
}
도움이 되었습니까?

해결책

Here's the correct code(I found out after asking the question) Silly mistake of not initializing the variable correctly.

#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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top