Make a file by yourself named ”Integer.txt” and add 5 integer values in it. Now, write a C++ program that reads data (5 integers) from the file and store them in integer array. Also make another integer array (int result []) of same size to store the results. The program should check for each number in array if it is prime number or not. If the number is prime, update value in result[] array from 0 to 1. Lastly, write output in another file named “Result.txt”
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
bool isprime(int n)
{
bool isPrime = true;
if (n == 0 || n == 1)
isPrime = false;
else
{
for (int i = 2; i <= n / 2; ++i)
{
if (n%i == 0)
{
isPrime = false;
break;
}
}
}
return isPrime;
}
int main()
{
const int N = 5;
int arr[N];
cout << "Please, enter 5 values: ";
for (int i = 0; i < N; i++)
{
cin >> arr[i];
}
ofstream of;
of.open("Integer.txt");
if (!of.is_open())
cout << "File isn`t opened!";
else
{
for (int i = 0; i < N; i++)
{
of << arr[i] << " ";
}
}
of.close();
int arrFromFile[N];
ifstream ifs("Integer.txt");
if (!ifs.is_open())
cout << "File isn`t opened!";
else
{
string line;
string str = "";
getline(ifs, line, '\n');
int k= 0;
for (int i = 0; i < line.size(); i++)
{
if (line[i] == ' ')
{
arrFromFile[k++] = stoi(str);
str = "";
}
else
str += line[i];
}
}
ifs.close();
int result[N];
for (int i = 0; i < N; i++)
{
if (isprime(arrFromFile[i]))
result[i] = 1;
else
result[i] = 0;
}
cout << "\nResult array: ";
for (int i = 0; i < N; i++)
{
cout << result[i] << " ";
}
ofstream ofr;
ofr.open("Result.txt");
if (!ofr.is_open())
cout << "File isn`t opened!";
else
{
for (int i = 0; i < N; i++)
{
ofr << result[i] << " ";
}
}
ofr.close();
}
Comments
Leave a comment