Grade 9 · Text filesCitește în română
Sum of the numbers on each line
Original: Suma numerelor de pe fiecare linie
The idea
Every line of date.in contains a few integers, an unknown number of them. We read the line with getline, then 're-read' it as a stream of numbers with istringstream (from <sstream>). For every line we write its sum to date.out, one per line.
Original description (Romanian)
Fiecare linie din date.in conține câteva numere întregi, în număr necunoscut. Citim linia cu getline, apoi o „recitim” ca pe un flux de numere cu istringstream (din <sstream>). Pentru fiecare linie scriem suma ei în date.out, pe câte un rând.
- Complexity
- O(L), where L is the total number of characters
- Grade
- Grade 9 (Clasa a IX-a)
- Chapter
- Text files
Examples
Input (date.in)
1 2 3 10 -4 7
Expected output (date.out)
6 6 7
The code
Comments are in Romanian, as in the original collection. Edit freely: you can reset at any time.
/*
* Titlu: Suma numerelor de pe fiecare linie
* Clasa: 9
* Capitol: Fișiere text
* Descriere: Fiecare linie din date.in conține câteva numere întregi, în număr
* necunoscut. Citim linia cu getline, apoi o „recitim” ca pe un flux
* de numere cu istringstream (din <sstream>). Pentru fiecare linie
* scriem suma ei în date.out, pe câte un rând.
* Complexitate: O(L), unde L este numărul total de caractere
*
* Exemplu
* Intrare:
* 1 2 3
* 10 -4
* 7
* Ieșire:
* 6
* 6
* 7
*/
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
ifstream fin("date.in");
ofstream fout("date.out");
string linie;
while (getline(fin, linie))
{
istringstream sirLinie(linie);
long long x, suma = 0;
while (sirLinie >> x)
{
suma = suma + x;
}
fout << 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.