The task is to write simple numbers to a binary file. Numbers are taken from the interval 1 ... n. I did everything, but I can't get numbers into the console. That is, count numbers from a file. Help me find a bug.

#include <iostream> #include <cmath> #include <fstream> using namespace std; bool IsPrime(int num) { for (int i = 2; i < sqrt(num); i++) { if (num % i == 0)return false; } return true; } int main() { fstream f; int n; cout << "Input N" << endl; cin >> n; f.open("f.bin", ios::app/ios::binary); for (int i = 1; i < n; i++) { if (IsPrime(i)) { f.write((char *) &i, sizeof(i)); } } f.close(); f.open("f.bin", ios::in / ios::binary); int a; while (f.eof()) { f.read((char *) &a, sizeof(a)); cout << a << " "; } f.close(); system("pause"); return 0; } 

    1 answer 1

    At least, it is not necessary to divide ...

     ios::app/ios::binary 

    need - bitwise OR:

     ios::app|ios::binary 

    In general, I would do this:

     bool IsPrime(int num) { if (num < 2) return false; if (num == 2) return true; if (num%2 == 0) return false; for (int i = 3; i*i <= num; i+=2) { if (num % i == 0) return false; } return true; } int main() { int n; cout << "Input N" << endl; cin >> n; { ofstream f("f.bin",ios::binary); for (int i = 1; i < n; i++) { if (IsPrime(i)) { f.write((char *) &i, sizeof(i)); } } } { ifstream f("f.bin", ios::binary); int a; while(f.read((char*)&a,sizeof(a))) cout << a << " "; } system("pause"); return 0; } 

    It is possible with one fstream , of course:

     bool IsPrime(int num) { if (num < 2) return false; if (num == 2) return true; if (num%2 == 0) return false; for (int i = 3; i*i <= num; i+=2) { if (num % i == 0) return false; } return true; } int main() { int n; cout << "Input N" << endl; cin >> n; fstream f; f.open("f.bin",ios::out|ios::binary); for (int i = 1; i < n; i++) { if (IsPrime(i)) { f.write((char *) &i, sizeof(i)); } } f.close(); f.open("f.bin", ios::in|ios::binary); int a; while(f.read((char*)&a,sizeof(a))) cout << a << " "; f.close(); system("pause"); return 0; } 

    Yes, the app flag is unsuccessful, the next time you start it, it will be added to the file - and you need it ...?