1
#include <iostream>
#include <fstream>

using namespace std;


int main()

{
    int a , b , c , d; 
    ifstream myfile;

    myfile.open ("numbers.txt");
    myfile >> a, b, c;
    d = a + b + c;

    ofstream myfile;
    myfile.open ("result.txt");
    myfile << d;
    myfile.close();

    return 0
}

The number.txt file contains 3 numbers 10 , 8 , 9. I am trying to get the program to read them and sum them up in the results.txt.

The errors I get are:

conflicting declaration 'std :: ifstream myfile'
no match for 'operator << in myfile << d'
'myfile' has a previous declaration as 'std :: ifstream myfile' 
olevegard
  • 5,294
  • 1
  • 25
  • 29

2 Answers2

3

(This only addresses one of the two errors in your code.)

myfile >> a, b, c;

This line doesn't read input to all three variables a, b, and c. It only reads input to a, then evaluates b and discards the value, then evaluates c and discards the value.

What you want is:

myfile >> a >> b >> c;

This will read a value to all three variables from myfile.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
2

You cannot declare two different variables with the same name. You are first declaring myfile to be of type std::ifstream and then later you declare myfile to be of type std::ofstream. Name your output stream variable differently.

Nikola Benes
  • 2,372
  • 1
  • 20
  • 33
  • that cleared 2 errors, thanks, the last error is: no match for 'operator << in myfile << d' – ParanoidParrot May 28 '15 at 08:43
  • You are probably still using the input stream for output. Use the output stream instead. – Nikola Benes May 28 '15 at 08:46
  • @ParanoidParrot Try renaming your variables more descriptively, e.g. `input` for your input file stream, and `output` for your output file stream, so you'll always know which one is which. – Emil Laine May 28 '15 at 08:51