In c++ I try to take input from a file and check if the number is prime or not. But the main problem is if one of the number isn't prime then next numbner is showng not prime ex-
my input in a file is 1 2 3 4 5 6
for first 3 digit it shows prime number when print num4 it says not prime after that all the input says not prime. Wht's the problem here is my code-
int main()
{
int x,i,b=0,j;
int a[15];//size of array more than number of entries in data file
ifstream infile;
infile.open("prog1_input.txt");//open the text file
if (!infile)
{
cout << "Unable to open file";
exit(1); // terminate with error
}
i=0;
while (!infile.eof())
{
//To make array for column
infile>>x;
a[i]=x;
for(j=2;j<x;j++)
{
if(x%j==0)
{
b++;
}
}
if(b==0)
{
cout<<a[i]<<"\t"<<"Prime"<<endl;
}
else
cout<<a[i]<<"\t"<<"Not Prime"<<endl;
// cout <<a[i]<<endl;
i++;
}
// To print entry
infile.close();
// getch();
}
in your code, b is never reset back to 0
What you need to do is this
if(b==0)
{
cout<<a[i]<<"\t"<<"Prime"<<endl;
} else {
cout<<a[i]<<"\t"<<"Not Prime"<<endl;
b = 0;
}
At first glance i would say that you have to reinitialize b at the beginning of the loop
if (!inline.eof())
If you have any question, please you are welcome :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.