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' 
3
  • 1
    The error message is obvious You cannot use same variable name myfile for both file streams.. Commented May 28, 2015 at 8:41
  • Maybe pick a different name for your ofstream? Commented May 28, 2015 at 8:41
  • 1
    You need to read about the comma operator. Commented May 28, 2015 at 8:42

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

that cleared 2 errors, thanks, the last error is: no match for 'operator << in myfile << d'
You are probably still using the input stream for output. Use the output stream instead.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.