c - looking for numbers in a character array -
i'm writing program reads lines file need print out numbers, lines read stored in character array:
char line[255]; //code read line file here (c=0;c<256;c++) { if (line[c]<58 && line[c]>47) printf("the character is: %c\n",line[c]); }
the configuration file has following lines:
buttons 3
the result i'd the character 3
, instead 3,9,4,4
hope i've provided sufficient information. thanks
your if-statement wrong.
you can express clearer, , more correctly as:
if ('0' <= line[c] && line[c] <= '9') { printf("the character is: %c\n",line[c]); }
your loop runs 256 characters, though input of "buttons"
has 7 characters. you're running off memory not yours, , finding 9, 4, 4, there random chance.
you want:
for (int c=0; c < 256; ++c) { if (line[c] == '\0') // if end of input found, stop loop. { break; } if ('0' <= line[c] && line[c] <= '9') { printf("the character is: %c\n",line[c]); } }
Comments
Post a Comment