错误消息:如果数字不是整数而是浮点数

问题描述 投票:0回答:2

为什么输入浮点数时不会出现错误?

int m;
if(scanf("%d%",&m)!=1)
{
    printf("Error\n");
    exit(1);
}
c if-statement scanf
2个回答
2
投票

0
投票
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <limits.h> int str_int ( char *line, int *value) { long int input = 0; char *end = NULL;//will point to end of parsed value if ( line == NULL) { return 0; } errno = 0; input = strtol ( line, &end, 10);//get the integer from the line. end will point to the end of the parsed value if ( end == line) {// nothing was parsed. no digits printf ( "input [%s] MUST be a number\n", line); return 0;// return failure } // *end is the character that end points to if ( *end != '\0') {// *end not '\0' printf ( "problem with input: [%s] \n", line); return 0; } if ( ( errno == ERANGE && ( input == LONG_MAX || input == LONG_MIN)) || ( errno != 0 && input == 0)){// parsing error from strtol perror ( "input error"); return 0; } if ( input < INT_MIN || input > INT_MAX) { printf ( "input: [%s] out of range %d %d\n", line, INT_MIN, INT_MAX); return 0; } if ( value == NULL) { return 0; } *value = input;// *value allows modification to callers int return 1;// success } int main( void) { char line[100] = ""; int number = 0; int valid = 0; do { printf ( "Enter number ( or quit)\n"); if ( ! fgets ( line, sizeof line, stdin)) {//read a line fprintf ( stderr, "fgets EOF\n"); return 1;//problem. exit program } if ( strcmp ( line, "quit\n") == 0) { return 0;// if quit is entered, exit the program } line[strcspn ( line, "\n")] = '\0';//remove newline valid = str_int ( line, &number);// call to parse a value } while ( !valid);// on failure, keep looping the above if ( valid) { printf ( "the number entered is %d\n", number); } return 0; }
© www.soinside.com 2019 - 2024. All rights reserved.