C Getting decimal input from user issue -
i'm trying write function decimal input user , return actual value converted ascii. however, function causes next input user skipped. in:
enter input: 123
enter input: /* doesn; allow input */
enter input: 456
long sum = 0; int character = fgetc(stdin); while(character != '\n'){ if(character >= '0' && character <= '9'){ /* convert ascii */ character -= '0'; sum = sum * 10 + character; } else{ /* reenter number */ } character = fgetc(stdin); } return sum;
to figure out why code doesn't work, suggest post full code, because problems may lie in way call function.
so before full code posted, can tell code works on machine:
#include <stdio.h> #include <ctype.h> int getlong(); int main() { printf("\t%d\n", getlong()); printf("\t%d\n", getlong()); return 0; } int getlong() { long sum = 0; int character = fgetc(stdin); while (character != '\n') { if (isdigit(character)) { /* convert ascii */ character -= '0'; sum = sum * 10 + character; character = fgetc(stdin); } else { character = fgetc(stdin); continue; } } return sum; } ctype.h included in order use isdigit(), while tells whether character decimal digit.
but in fact, don't have on own. using standard library more effective , efficient, both , computer.
for example, can scan long integer directly stdin:
#include <stdio.h> int main() { long value; puts("please input numbers:"); while (scanf(" %ld", &value) != 1) { puts("only numbers welcome:"); scanf("%*[^\n]"); } printf("%ld", value); return 0; } notice white-space @ beginning of format, makes scanf() discard white-space characters(including spaces, newline , tab characters) extracted until non-white-space character met.
or, use strtol(), while relatively seen:
#include <stdio.h> #include <stdlib.h> int main() { char buf[80]; char *pend; long value; { puts("numbers please:"); if (fgets(buf, 80, stdin) == null) { perror("fgets()"); return 1; } value = strtol(buf, &pend, 10); } while (*pend != '\n'); printf("%ld", value); return 0; } of course, sscanf() works, can write code on own.
Comments
Post a Comment