简体   繁体   English

检查用户输入的数字

[英]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() . 它使用getchar()创建文件并在其中存储数据(由用户直到输入流或Ctrl + Z的末尾 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. 我已经阅读了许多主题,所有答案都建议使用isdigit()但它不能验证带有浮点数的数字。 Here's my isNumeric() function: 这是我的isNumeric()函数:

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. 此处的根本问题是isNumeric旨在确定字符串是否为有效数字,但是您一次只给isNumeric一个字符。

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. 要解决此问题,您需要一个存储字符的char数组,直到到达该数组应包含完整数字的位置为止。 Then check the array with isNumeric . 然后使用isNumeric检查数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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