#include<iostream> #include<cstdio> using namespace std; int main() { freopen("y.in", "r", stdin); freopen("y.out", "w", stdout); int a, s = 0; while(scanf("%d", &a)) { s += a; } cout << s << endl; return 0; } 

The input file contains n integers. It is necessary to output a single integer - the sum of all in the input file. I tried to do as shown above and fails. Tell me what to do to make it work.

Is it possible to do this with the cin construct? not scanf ()

  • I ask you to suggest methods that can earn in the console, if I comment out // freopen - risonyo

4 answers 4

Write the condition correctly

 while(scanf("%d", &a) == 1) 

And everything will work.

And a small note - do not mix "sishny" - scanf input and "c ++" output of std :: cout.

Why is your condition not working? scanf returns the number of read numbers. And in your case, it will return 1. But when the data runs out, it will return -1 . And that while that you have written is equivalent to this:

 while(scanf("%d", &a) != 0) 
  • ok, I will consider, thank you - risonyo
  • and freopen () it or s ++ function? - risonyo
  • generally sishnaya. But you can not say so, to be honest. It can (and sometimes should) be used in c ++. The main thing is not to mix styles. - KoVadim
  • one
    >> And that while that you wrote is equivalent to this: >> while (scanf ("% d", & a)! = 1) Probably the same ! = 0 ? - nitrocaster
  • probably :) - KoVadim

@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.

    Way through C ++ threads

     #include <fstream> #include <iostream> using namespace std; int main() { ifstream in("input.txt"); //создаём поток ввода из файла ofstream out("output.txt"); //создаём поток вывода в файл int a=0,s=0; while(true) { in>>a;//читаем из потока(файла input.txt) одно значение if (in.eof()) break; s+=a; } cout<<s; //вывод сумму на консоль //out<<s; вывод суммы в поток(файл output.txt) in.close(); out.close(); return 0; } 

    cin reads data from the console. I do not know, maybe using it and you can read the data from the file, but this will already be some kind of perversion, in my opinion.

    • and through cin it is possible? - risonyo
    • added to the end of the answer at the expense of cin. - STIZZ
    • 2
      while (! in.eof ()) // the eof () method returns 1 if it reached the end of the file {in >> a; // read from the stream (file input.txt) one value s + = a; } A gross error in determining reaching the end of the file. The eofbit flag eofbit set only after an operation has been attempted (for example, reading) outside the file. Those. it is necessary to write like this while (true) // the eof () method returns 1 if you have reached the end of the file {in >> a; // read from the stream (file input.txt) one value if (in.eof ()) break; s + = a; } - skegg
    • one
      Another good way: always explicitly close the in.close () file streams; - skegg
    • one
      And after entering the number, you must first check in.good (), and only then (if not gud) at eof. while (1) {in >> a; if (! in.good ()) break; // and eof too ....} if (i.eof ()) OK; else ERR; - avp
     while(true) { in>>a;//читаем из потока(файла input.txt) одно значение if (in.eof()) break; s+=a; } 

    it is better to use a post-conditional loop (no need to do extra checks)

     do { in >> a; s += a; } while( !in.eof() ); 
    • one
      @ vitali0, try entering a letter instead of a number and see what happens. - avp
    • See what happens. Suppose it counts n numbers from a file and reaches its end. When trying to read a new number, an error occurs and the variable a does not change, but also contains the last read value. Then this value is again added to the total amount and the cycle ends. See a mistake? And the total number of checks in the loop will not change. - skegg
    • This is an error with normal numbers (it is still necessary to realize it), and with a letter it will simply go in cycles. Don't know what is best for learning? - avp
    • @mikillskegg, @avp about the checks on the correctness of the input You are right, I did not provide for this - vitali0