如果语句检查用户是否输入了有效的双号

时间:2017-06-30 23:15:30

标签: c

我正在尝试创建一个程序来检查用户是否输入了有效的双号。 我知道如何通过执行以下操作来检查有效整数:

if (scanf("%d%c", &inter, &newLine) != 2 || newLine != '\n') 

但是当检查双重类型时,它不起作用。

我试过了:

if (scanf("%d%c", &inter, &newLine) != 2.00 || newLine != '\n') 

if (scanf("%d%c", &inter, &newLine) != 2.000000 || newLine != '\n') 

似乎没有任何工作

这是一个如何检查有效整数类型的完整示例;

do {
    num = inter % 1;

    if (scanf("%d%c", &inter, &newLine) != 2 || newLine != '\n') {

        printf("Invalid integer, please try again: ");

        flushKeybord();
    } else {
        x = x + 1;
    }
} while (x == 0);

其调用的函数,如果它的无效只是一个清除缓冲区

1 个答案:

答案 0 :(得分:1)

另一个scanf主题。请勿使用scanf,请阅读fgets行,然后使用sscanfstrtok等解析。请参阅Why does everyone say not to use scanf? What should I use instead?

此外,scanf会返回成功匹配和分配的输入项目数。

//编辑:使用strtod进行以下操作:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(void)
{
    char line[1024];
    double d;
    char *pEnd;

    for(;;)
    {
        // here you should check if fgets returns NULL
        fgets(line, sizeof line, stdin);

        int len = strlen(line);

        if(line[len-1] == '\n')
            line[len-1] = 0;

        d = strtod(line, &pEnd);    

        if(*pEnd == 0 && len > 0)
        {
            printf("Double: %lf\n", d);
            return 0;
        }

        printf("Wrong format, try again\n");
    }

    return 0;
}