Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

WinkeyFaced

macrumors newbie
Original poster
Sep 19, 2011
2
0
Hey I am having some trouble with this one. My teacher asked us to make a program that asks the user to read a file (numbers.txt and words.txt) and output the sum. For the words.txt we have to tell the computer to skip over words and just use the numbers.

heres the numbers.txt
7
9
13
18
10
12
4
18
3
6

and the words.txt
Set1
7
9
13
Set2
18
10
12
4
Set3
18
3
6
and heres my program

PHP:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <sstream>

using namespace std;

int main() 
{
   string filename;
    cout << "Please enter the filename: ";
    getline(cin, filename);
    
    ifstream file(filename.c_str());
    
    int number;
    int sum;
    
    if (!file.good()) //if the file isn't there
    {
        cout << "Sorry, I can't find that file." << endl;
    return 0;
    }
    else //if the file is there
    {
        file >> number;
    
     while (!file.eof()) //while the file hasn't ended
     {
         int num;
         file >> num;
         sum += num; //sum now = sum + num
     }
       
         cout << "The sum is: " << sum << endl;
     
    }
}

whenever I run it, it keeps giving my 99 when the answer is 100. and im lost on the words.txt one. Please help!
 
Last edited by a moderator:

willieva

macrumors 6502
Mar 12, 2010
274
0
Learning how to debug code is as important as learning how to write it. If you're not sure of what the code is doing, a few well placed cerr's will generally enlighten you. If you want to see what is going wrong with the summation, put a:
cerr << "sum " << sum << endl;

That will at least help you find out what is going wrong when reading numbers.txt.

Using cerr or cout in this context is basically the same, but when you start writing more complex code that crashes, using cerr and endl will allow you to see errors that using cout will miss. It's never too early to develop good habits.

And in unix land, the return of a program should be zero for success, not failure. If the file isn't there, you shouldn't be returning a zero.
 

wlf

macrumors member
Jun 21, 2010
54
100
2 problems I can see:

- sum is not initialised (to zero) so contains some random value
- the first number read is not added to sum (just after the else)

I don't think the first

file >> number;

should be there at all.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.