Advertisement
cd62131

input number

Jul 10th, 2014
488
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.81 KB | None | 0 0
  1. #include <ctype.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. int main(void) {
  6.   char buf[7];
  7.   int i, number;
  8.   while (1) {
  9.     printf("入力: ");
  10.     fgets(buf, 7, stdin);
  11.     buf[strlen(buf) - 1] = '\0';
  12.     if (strlen(buf) == 0) {
  13.       fprintf(stderr, "入力がありません\n");
  14.       goto error;
  15.     }
  16.     for (i = 0; i < strlen(buf); i++) {
  17.       if (i == 0 && (buf[0] == '+' || buf[0] == '-')) continue;
  18.       if (!isdigit(buf[i])) {
  19.         fprintf(stderr, "半角正数以外は全て入力無効です\n");
  20.         goto error;
  21.       }
  22.     }
  23.     number = atoi(buf);
  24.     if (number < 0) {
  25.       fprintf(stderr, "マイナスの値には絶対になりません\n");
  26.       goto error;
  27.     }
  28.     break;
  29.     error: ;
  30.   }
  31.   printf("input: %d\n", number);
  32.   return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement