@risonyo, after freopen(...,stdin/stdout)
cin
/ cout
will work with the file.
I thought you had already dealt with all this for a long time, but if you are interested, see:
#include <iostream> #include <cstdio> #include <cerrno> #include <cstring> using namespace std; /* * ΠΠ΅ΡΠ΅ΠΎΡΠΊΡΡΠ²Π°Π΅Ρ Ρ Π·Π°Π΄Π°Π½Π½ΡΠΌΠΈ ΡΠ°ΠΉΠ»Π°ΠΌΠΈ stdin, stdout * ΠΈΠ»ΠΈ ΠΏΠ΅ΡΠ°ΡΠ°Π΅Ρ help * * Returns 0 if OK */ static int do_inout (int ac, char *av[]) { if (av[1]) { if (strcmp(av[1], "-h") == 0 || strcmp(av[1], "--help") == 0) { cerr << "Usage: " << av[0] << " [input-file|- [output-file]]\n" << " `-' means stdin\n"; return -1; } if (strcmp(av[1],"-")) if (!freopen(av[1], "r", stdin)) { cerr << "Can't freopen stdin to " << av[1] << " : " << strerror(errno) << '\n'; return 1; } if (av[2]) if (!freopen(av[2], "w", stdout)) { cerr << "Can't freopen stdout to " << av[1] << " : " << strerror(errno) << '\n'; return 2; } } return 0; } int main (int ac, char *av[]) { int err = do_inout(ac, av); // Returns -1 Π΅ΡΠ»ΠΈ help ΠΏΡΠΎΡΠΈΠ»ΠΈ if (!err) { int sum = 0, a; while (1) { cin >> a; if (cin.good()) sum += a; else break; } if (cin.eof()) cout << "Sum: " << sum << '\n'; else { err++; cerr << "Read error\n"; } } return err > 0 ? 1 : 0; // ΠΏΡΠΈ ΠΎΡΠΈΠ±ΠΊΠ΅ Π²ΠΎΠ·Π²ΡΠ°ΡΠΈΠΌ 1, Π΅ΡΠ»ΠΈ OK ΠΈΠ»ΠΈ help, ΡΠΎ Π²Π΅ΡΠ½Π΅ΠΌ 0 }
When run without arguments, reads and writes to the console. The first argument is the name of the input file, the second is the output. If the first argument -
then reads the console, and if -h
or --help
- prints:
Usage: ./a.out [input-file|- [output-file]] `-' means stdin
When you try to enter a non-integer number, it writes an error message and ends with code 1.
What is not clear - ask.