Write a C++ program that reads a sequence of integer numbers from the input file data.txt. The sequence ends with a sentinel value of zero. The program should output the following into an output file results.txt:
Use the following values in the file data.txt to test your program:
5
4
-8
-7
6
-2
9
#include <fstream>
#include<iostream>
using namespace std;
int main() {
int arr[30];
ifstream file_in("data.txt");
int count= 0;
int x;
while (count < arr[30] && file_in >> x)
arr[count++] = x;
ofstream file_out("results.txt");
file_out<<"The integers are:"<<"\n";
for (int i = 0; i < count; i++) {
file_out << arr[i] <<' ';
}
int count_pos=0;
int count_neg=0;
int sum_pos=0;
int sum_neg=0;
for(int i=0;i<count;i++){
if(arr[i]>0){
sum_pos=sum_pos+arr[i];
count_pos++;
}
else if(arr[i]<0){
sum_neg=sum_neg+arr[i];
count_neg++;
}
}
file_out<<"\nThe number of positive numbers are: "<<count_pos;
file_out<<"\nThe number of negative numbers are: "<<count_neg;
file_out<<"\nThe sum of negative numbers are: "<<sum_pos;
file_out<<"\nThe sum of negative numbers are: "<<sum_neg;
file_out.close();
file_in.close();
}
Comments
Leave a comment