Grade 9 · Text filesCitește în română

Reading until the end of the file

Original: Citirea până la sfârșitul fișierului

O(n)C++1736 lines1 exampleuses date.in / date.out

The idea

The file date.in contains integers, but we do not know how many. The expression fin >> x returns 'true' as long as reading succeeds and 'false' at the end of the file, so it can be the loop condition itself. date.out receives how many numbers there were and their sum.

Original description (Romanian)

Fișierul date.in conține numere întregi, dar nu știm câte. Expresia fin >> x întoarce „adevărat” cât timp citirea reușește și „fals” la sfârșitul fișierului, deci poate fi chiar condiția buclei. În date.out se scriu câte numere au fost și suma lor.

Complexity
O(n)
Grade
Grade 9 (Clasa a IX-a)
Chapter
Text files

Examples

Example 1

Input (date.in)

3 8 -1
10

Expected output (date.out)

4 20

The code

Comments are in Romanian, as in the original collection. Edit freely: you can reset at any time.

citire-pana-la-sfarsitul-fisierului.cpp
/*
 * Titlu: Citirea până la sfârșitul fișierului
 * Clasa: 9
 * Capitol: Fișiere text
 * Descriere: Fișierul date.in conține numere întregi, dar nu știm câte. Expresia
 *            fin >> x întoarce „adevărat” cât timp citirea reușește și „fals” la
 *            sfârșitul fișierului, deci poate fi chiar condiția buclei.
 *            În date.out se scriu câte numere au fost și suma lor.
 * Complexitate: O(n)
 *
 * Exemplu
 * Intrare:
 * 3 8 -1
 * 10
 * Ieșire: 4 20
 */
#include <fstream>
using namespace std;

int main()
{
    ifstream fin("date.in");
    ofstream fout("date.out");
    long long x, suma = 0;
    int numar = 0;
    while (fin >> x)
    {
        numar++;
        suma = suma + x;
    }
    fout << numar << ' ' << suma << '\n';
    fin.close();
    fout.close();
    return 0;
}

Runs on a real g++ (C++17, -O2) through Compiler Explorer. Keep runs short; there's a time limit.