i/ostreams

Can I ask where did I go wrong in the code? It was supposed to add the numbers infile (1,2,3,4)

#include <fstream>

int main( )
{
using namespace std;
ifstream in_stream;
ofstream out_stream;

in_stream.open("infile.dat");
out_stream.open("outfile.dat");

int first, second, third;
in_stream >> first >> second >> third;
out_stream << "The sum of the first 3\n"
<< "numbers in infile.dat\n"
<< "is " << (first + second + third)
<< endl;

in_stream.close( );
out_stream.close( );

return 0;
}
What exactly is in "infile.dat" and what output do you get?
We need to extract (and discard) the comma characters used as the separator between the numbers 1,2,3...

1
2
3
4
5
6
7
8
9
10
11
12
13
if( std::ifstream in_file{"infile.dat"} ) // if the file is opened for input
{
    int first, second, third ;
    char comma ;
    if( in_file >> first >> comma >> second >> comma >> third ) // may be validate comma == ',' after each read
    {
         // add the numbers etc.
         // ...
    }
    else std::cerr << "badly formed input data\n" ;
}

else std::cerr << "failed to open input file\n" ;
Topic archived. No new replies allowed.