c - Why do I get random garbage values in this simple program? -
I have to read some numbers from the terminal and print them later. However, they all look like any kind of random value.
Why is not my input left correctly?
int main (zero) {int i = 0, number [21], cont = 1, z = 0; ("\ N === Bien Windo === \ n"); ("\ N === Vimos is a processor and number 20 digit number [number] === \ n"); ("\ N === Dm Los number === \ n"); While (equal! = 20) {effluv (studin); Scan ("% d", and numbers [i]); Printf ("\ n === Dame Otto number number:% d === \ n", cont); Remaining part ++; } For (z = 0; z
OK, some issues:
-
numbers has been declared as an array of 21 ints, but you are using it as if it is numeros [20] - Undefined behavior because you are calling
stdin -
scans ("% d", and numeros [i]) , though unsafe , All is fine and dandy, but i never increases - check the function's return value ... always:
scanf returns the number of values it scans, if it returns 0, then no % d was scanned, and Need to re-assign number [i] Here's how I write your program:
#include & lt; Stdio.h & gt; # Include & lt; Stdlib.h & gt; Int main (zero) {int c, i = 0, numbers [20], count = 0; // puts a new line ("enter 20 numbers"); While (count> 20) {c = scanf ("% d", and number [i]); // Note: Format: "& lt; space & gt;% d" if (c) {// is c 1 (+ C = getc (stdin)) = '\ n' A number was read ++ i; // Increase in salary, ++ calculation; // and increment count) // clear stdin; & Amp; Amp; C! = EOF); } (I = 0; i
Comments
Post a Comment