0

I'm supposed to write a program that reads positive integers from a file and finds the sum of the even numbers as well as the sum of the odd numbers and outputs it.

I can't get the input file to be read correctly, right now it just outputs a very large negative number. I've looked at different forums for help but I still don't understand.

This is the code I have so far:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream infile;
    int evenSum = 0, oddSum = 0;
    int num;
    infile.open("integers.txt");

    //infile >> num;
    //cout << "The numbers entered are: " << endl;
    //cout << num;

    while (infile >> num)
    {
        //num++;

        if (num % 2 == 0)
            evenSum = evenSum + num;
        else
            oddSum = oddSum + num;

        //infile >> num;

    }
    cout << "The numbers entered are: " << endl;
        cout << num;

    cout << "\n\n\nEven sum: " << evenSum << endl;
    cout << "Odd sum: " << oddSum << endl;

    infile.close();

    return 0;
}

I have some lines comment-blocked out because I was testing things and I'm not sure if I need it or where to put those things.

For reference here are the integers from the file:

30 20 15 17 22 26 29 33 35 86 40 41 49 23 11 9 6 55 16 77

Here is also a sample output of what it should look like:

sample output

any help or feedback is highly appreciated

anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • 3
    Have you confirmed the file actually opened correctly (`infile.fail()`/`infile.is_open()`)? – scohe001 Apr 05 '21 at 22:13
  • 1
    `cout << num;` should be inside a `while (infile >> num)` loop, otherwise you are dumping only the last number. – user3124812 Apr 05 '21 at 23:19
  • @scohe001 yeah so it looks like the file is not actually opening. i have the actual file itself already open on notepad as im running the code but its not opening there?? how do i fix that? – virtualsoph Apr 06 '21 at 20:21
  • Is the file in the directory your terminal is CD'd into when you're running the program? If not, you either need to fix the relative path or use a full path. – scohe001 Apr 06 '21 at 20:24
  • @scohe001 ok i figured out that part. now the file opens correctly. now the issue is the when it outputs the numbers from the file, it does not include the white space in between the numbers so it just outputs them all smushed together. how do i get it to read the white spaces as well? – virtualsoph Apr 06 '21 at 22:44

0 Answers0