![]() ![]() | chars/int-read-1.c - En mere brugbar udgave med mulighed for fortegn og bedre linieafslutning. | Lektion 10 - slide 9 : 51 Program 3 |
#include <stdio.h> #include <stdlib.h> int read_int(); int main(void) { int i, n = 0; for (i = 1; i <= 5; i++){ printf("Enter an integer: "); n = read_int(); printf("Decimal value: %d\n", n); } return 0; } int read_int(){ int res = 0; char c; int sign = 1; /* Handle initial sign, if any */ c = getchar(); if (c == '+') {sign = 1; c = getchar();} else if (c == '-') {sign = -1; c = getchar();} else if (isdigit(c)) {sign = 1;} else {printf("Int read error"); exit(EXIT_FAILURE);} /* Read digits - first char is ready in c*/ while (isdigit(c)){ res = res * 10 + (c - '0'); c = getchar(); } /* Read the rest of the line */ while (c != '\n') c = getchar(); return sign * res; }