检查用户输入的数字

标签 c

在我的主要功能中,我有以下内容:

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;
}

它创建一个文件并使用 getchar() 在其中存储数据(由用户直到输入流结束或 Ctrl+Z)。我想检查提供的数据是否为数字,但我遇到了困难。我读过很多主题,所有答案都建议 isdigit() 但它不会用 float 验证数字。这是我的 isNumeric() 函数:

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

最佳答案

这里的根本问题是 isNumeric 旨在确定 string of characters 是否为有效数字,但您只提供 isNumeric 一次一个字符。

要解决此问题,您需要一个 char 数组来存储字符,直到到达数组应包含完整数字的位置为止。然后使用 isNumeric 检查数组。

关于检查用户输入的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27464685/

相关文章:

c - 让 libspotify 中的示例在 Windows 7 下工作

c - 从IOCCC 2013解说一位美国总统的类轮派对

c - 如何在没有任何错误的情况下将文本稳健地复制到 char*

c - 为什么 gcc (ARM) 不使用全局寄存器变量作为源操作数?

java - C 错误的 JNI 访问对象数组

c - AV编解码器: not able to decode hevc

c - 如何防止 fget 在缓冲区溢出时多次运行?

c++ - 快速排序后进行二进制搜索是否比线性搜索更快?

c++ - 由于某种原因必须发送 MPI 消息两次

c - 如何验证给定散列和公钥的数字签名?