input

#include <fstream>
#include<iostream>
#include <iomanip>
#include <stdlib.h>
#include <conio.h>
using namespace std;
#define size 3

void main()
{
int arr[10],sum=0;
ifstream infile;
infile.open("input.txt", ios::in);
if (infile.fail()){
cerr<< "Input file cannot open ";
exit(-1);
}
while(!infile.eof()){
for(int i=0; i<10; i++)
{
infile >> arr[i];
cout <<setw(4)<< arr[i];
sum += arr[i];
}
infile.close();
cout << sum;

}
_getch();
}
Input file can be read but it will read twice.Why?
What do you mean it will not read twice? Also you don't need to give an ifstream the in flag , you only need that for fstreams since they can be in or out.

Also I believe you should have

1
2
3
4
5
6
while( !infile.eof() ) //or better to use good()
{
    infile >> arr[i];
    cout << setw(4) << arr[i];
    sum += arr[i];
}
Last edited on
closed account (Dy7SLyTq)
a) use cstdlib.
b) use int main
c) what do you mean read twice? like the file contains 5 ints and fills all 10? i feel like the problem is in your nested loops
for example, the input is 5,10,15, so the sum is 30.
then output will be 5, 10 , 15 , 30, 5 , 10, 15, 60.
Thank you
Topic archived. No new replies allowed.