H
H
hell0_w0rld2018-11-04 17:13:18
assembler
hell0_w0rld, 2018-11-04 17:13:18

How to read a line from a file and write the numbers to an array?

I was given an input.txt file, which contains a line where numbers are indicated separated by a space (their number is unknown). You need to know their sum.
I don't understand the algorithm.
I'll offer my own
0. We read the data, but in order to count, it seems, you need to know the length of the string (Now a brilliant idea has come - find out the file size and divide by 2)
1. Take the si element of the array.
2. Check for a space
3. If there is a space, then go to the label num2arr. (In this label, we create a cycle with di iterations (i = from 0 to di-1). We pull out a digit character from the stack, convert the character into a digit (bx), perform such an operation - ax = (i * 10) + bx and so further to the end of the loop.Then we write ax to the array (one more variable is needed there))
4. If it's a number, then put it on the stack. We add some other variable, for example, di
But it seems to me that everything is confusing here and it can be easier. Tell me how.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2018-11-04
@hell0_w0rld

I was given an input.txt file, which contains a line where numbers are indicated separated by a space (their number is unknown). You need to know their sum.
...
it seems to me that everything is confusing here and it can be easier. Tell me how.

do not create intermediate arrays, count everything on the fly:
0) you need to keep the current sum (S), initialize it with zero
1) you need to keep the value of the number read at the moment (V), initialize it with zero
2) read from the file character by character
-- if read character -- digit (d), add it to the current number: V = V * 10 + d
-- if the character read is a non-digit or end-of-file, add the current number to the sum and set the current number to zero: S = S + V ; V = 0
3) if the end of the file, then output S and finish the job, otherwise continue with step 2

K
Kalombyr, 2018-11-04
@Kalombyr

You don't need to know the length of the string.
For help: https://ru.cppreference.com/w/cpp/string/basic_str...
and the >> operator (skips a space by default, so you can get numbers right away).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question