Count lines problem (File stream)

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
Last edited on
This:

1
2
3
4
5
6
7
8
inputfile>>value;
while(!inputfile.eof())
{
total += value;
++count;
cout<<"("<<count<<") "<<value<<endl;
inputfile>>value;
}


can be replaced with this:
1
2
3
4
5
6
while(inputfile >> value)
{
    total += value;
    ++count;
    cout<<"("<<count<<") "<<value<<endl;
}


Also before you do this:
getline(inputfile,line);

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
Last edited on
Take it up from here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#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' ;
}



Thank you for your help. It works now!
Topic archived. No new replies allowed.