-
Problem writing to file
First of all, hello, I'm new here.
I have been trying to hack together a number tester, which will test a number to see if it's a prime or not. It should write the result to a file, but it doesn't. I've also been trying to figure out the source of the problem, but I just don't get it.
Here it is, to it's fullest:
Code:
// The program should test a number, defined by user-input, if it's a prime number or not.
// This through dividing each number below the user-inputted, starting from 2
// to, let the user-input be k, k-1. If all cases return a remainder, the number first inputted
// number is a prime.
// If none of the cases have a remainder the number is not a prime.
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
int main ()
{
int true_false, quit;
float i, k, result;
result = fmod(k, i);
i = 2;
cin >> k;
ofstream primefile;
primefile.open ("Primeer.txt", ios::ate);
if (!primefile.is_open())
{
cout << " The file could not be opened. ";
}
else
{
while (i = k - 1)
{
result = fmod(k,i);
if (result = 0)
{
true_false = true_false + 1;
break;
cout << " The following number isn't a prime: " << k;
primefile << " The following number isn't a prime: " << k;
primefile.close();
cout << " Succesfull writing to file: " << primefile;
}
if (result > 0)
{
true_false = true_false + 0;
i++;
}
}
}
if (i = k - 1, true_false = 0)
{
cout << " The following number is a prime: " << k;
primefile << " The following number is a prime: " << k;
cout << " Succesfull writing to file: " << primefile;
}
cin >> quit;
if (quit == true)
{
return 0;
}
}
Hope I didn't screw the formatting up.
Any help would be appreciated.
-
Quote:
Originally Posted by
Imagine
Code:
while (i = k - 1)
// ...
if (result = 0)
// ...
if (i = k - 1, true_false = 0)
// ...
Is this really what you meant?
-
Well, what's the error(s)?
-
What do you mean Jimzy? I think I made a mistake, it should be:
Code:
while ( i<k )
{
//...
}
The problem I'm having is that the program doesn't output any data, whatsoever.
-
= is assignment, == is test for equality. For example,
means set the value of result to 0 and never execute the code block, since the value of the expression "result = 0" is 0, which evaluates to false.
-
As robatino explained.
By assigning 0 to result, this
Code:
if (result = 0)
{
// ...
}
won't be true, and code inside this if won't execute. Same story goes for:
Code:
if (result > 0) // result is 0 after previous assignment
and
Code:
if (i = k - 1, true_false = 0)
Just fix ifs conditions and it should help.
-
Thanks very for pointing that out. Forgot about that.