简体   繁体   中英

Checking user input for numbers

In my main function, I have the following:

int main(){

    FILE *fp;
    char ch;
    char name[100];

    printf("Create file with name: ");
    scanf("%s", &name);

    fp = fopen(name, "w");
    printf("Enter data to be stored in the file: ");

    while((ch=getchar())!=EOF){
        if(isNumeric(ch)){
            putc(ch,fp);
        }
    }

    fclose(fp);

    return 0;
}

Which creates a file and stores data (by the user till the end of the input stream or Ctrl+Z) in it with getchar() . I want to check if the supplied data has been numerical but I'm hitting a rock. I've read many topics and all answers suggest isdigit() but it doesn't validate numbers with a floating point. Here's my isNumeric() function:

int isNumeric (const char * s)
{
    if (s == NULL || *s == '\0' || isspace(*s))
      return 0;
    char * p;
    strtod (s, &p);
    return *p == '\0';
}

The fundamental problem here is that isNumeric is designed to determine whether a string of characters is a valid number, but you're only giving isNumeric one character at a time.

To fix the problem, you need a char array that stores characters until you reach a point where the array should contain a complete number. Then check the array with isNumeric .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM