So I'm trying to count the number of lines in a text file that is inputed by the user. Also the code doesnt sum up the last number of the text file (exmp it calculates and print only 14 from 15 numbers). I'm a biginner in c++ programing. I would be greatful for any help!
Thank you
You need to set the position cursor back to the beginning of the file: inputfile.seekg(std::ios::beg);
EDIT: To count number of lines, you need to call getline(inputfile,line); more than once. That is unless you know the file only contains one line, then what is the point of counting it?
Also for future posts, place your code in code tags: EDIT > ctrl + A > look to your right > press this (<>) ->submit
#include <iostream>
#include <fstream>
#include <string>
// using namespace std;
int main()
{
std::string filein ;
std::cout << "Enter the input file name: ";
std::cin >> filein;
std::ifstream inputfile( filein.c_str() ) ; // constructor opens the file
if( !inputfile )
{
std::cout<<"The file could not be opened!\n";
return 1 ;
}
// read through to end of file, updating count and total as we go along
float total = 0 ;
int count = 0 ;
float value ;
while( inputfile >> value ) // canonical, check for failure as we read
{
total += value ;
++count ;
}
std::cout << "count: " << count << " total: " << total << '\n' ;
// inputfile is in a failed state now
// before we can read the file again:
inputfile.clear() ; // 1. clear the error state
inputfile.seekg(0) ; // 2. and seek to the begining of the file
// now we can start reading from the begining again, line by line this time
int nlines = 0 ;
std::string line ;
while( std::getline( inputfile, line ) ) ++nlines ;
std::cout << "#lines: " << nlines << '\n' ;
}