Ask user to enter 10 numbers and write them in a file “Numbers.txt” (5). After writing, check the file and count all the even numbers and odd numbers written in the file (10). Display the count of even and odd numbers on the screen.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
const string fileName="Numbers.txt";
ofstream numbersFile;
numbersFile.open(fileName);
int number;
//Ask user to enter 10 numbers
for(int i=0;i<10;i++){
cout<<"Enter number "<<(i+1)<<": ";
cin>>number;
//write them in a file "Numbers.txt"
numbersFile << number<<"\n";
}
//close the file "Numbers.txt"
numbersFile.close();
int evenCounter=0;
int oddCounter=0;
//After writing, check the file count all the even numbers and odd numbers written in the file.
ifstream numbersFileRead(fileName);
if (numbersFileRead.is_open()){
while (numbersFileRead>>number){
if(number%2==0){
evenCounter++;
}else{
oddCounter++;
}
}
numbersFileRead.close();
}
//Display the count of even and odd numbers on the screen.
cout<<"\nThe count of even numbers: "<<evenCounter<<"\n";
cout<<"The count of odd numbers: "<<oddCounter<<"\n";
system("pause");
return 0;
}
Comments
good job
Leave a comment