The practical solution
You should know a little bit about file manipulation and IO, and their syntax in C.
To read, you should just check where appear the ';'
, and at these intervals use fscanf with integer syntax. To write, use fprintf with string syntax, for each printed number, print the break character.
The manual solution
The first step is to know the size of the number. For this you iterate character by character until you find your break character (which in this case is ';'
). For this, you will pick up characters (using fgetc
), one by one and compare with the break character. If it is not, you should remove the value equivalent to the character '0'
. This is what you forgot to do. And then add to a fifo structure (page in English). When you find the break character, you instantiate it and do the same thing (this kind of thing is easier to do with object orientation). After you have all these queues, you use a concept of our numerical system. For example, 21 = 2*10^1 + 1*10^0
, 432 = 4*10^2 + 3*10^1 + 2*10^0
. If you notice that the values are multiplied by powers of 10, where the largest digit is multiplied by 10 (position - 1). Then, you use this logic:
enquanto o arquivo não estiver no fim:
caractere = arquivo.le_caractere()
enquanto caractere não for ';'
queue.push(caractere - '0')
caractere = arquivo.le_caractere()
lista_de_queues += queue
para cada queue em lista_de_queues:
enquanto houver itens no queue:
numero += queue.pop() * 10^queue.size()
lista_de_numeros += numero
Note that Queue.size() is necessarily the old size - 1, because by precedence, pop is called first. That way you can read the numbers.
Fortunately, to save is even easier! You must do the opposite operation, to extract a digit, and then save it as a char, added to '0'
. The number of digits in a number is its logarithm in base 10. It transforms this into integer, and goes on to do the following using a lifo structure:
for(unsigned i = 1; i <= digitos; i++)
stack.push( int( (numero % 10^i) / 10^(i-1) ) )
// nesse ponto, estarão na pilha, na ordem inversa. como é uma estrutura LIFO,
// ele vai nos devolver os dígitos na ordem correta
enquanto houver itens na pilha:
arquivo.escreve_caractere(stack.pop() + '0')
Negative numbers, just check if the first character is '-'
. If it is, multiply the final number by -1.
Already tried to use fprintf to write and fscanf to read ?
– Felipe
I got it from fprintf and fscanf, thank you
– Leonardo