仅输入数字而不是数字和字符串的集合

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

我输入此代码是为了让用户不输入字符串而只输入数字,但是当输入类似 55ST 程序接受 55 的内容时,不要将 55ST 视为字符串

printf("Enter the deposit amount L.E :");
                if (scanf("%lf", &money) != 1)
                {
                    printf("Invalid input. Please enter a number.\n");
                    while (getchar() != '\n')
                        TypeTransaction = 1;
                    continue;
                }

仅当用户输入类似 55SSYTF 的内容时,我才需要用户输入号码,我想阻止他

c scanf
1个回答
0
投票

scanf
不是最好的工具,您可以使用
fgets
+
strtol
功能:

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

int main()
{
    long number;
    char buffer[100];
    char *end;

    puts("enter a number:");
    if (!fgets(buffer, sizeof buffer, stdin))
    {
        puts("can't read input");
        return 0;
    }

    number = strtol(buffer, &end, 10);
    if ((0 != errno) || (end == buffer)  || (*end && *end != '\n'))
    {
        puts("can't decode input");
    }
    else
    {
        printf("Number:%ld.\n", number);
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.