Atoi函数无法正确转换字母

问题描述 投票:0回答:1
 printf("Enter a number or type 'Exit' to exit\n");

    long val = 0;
    int y = 3;

    scanf("%s", input);

    val = atoi(input); 


    if (val < y) {

       printf("Hey You!");

    }
    else {
        printf("Error, no such cell exists.\n");
    }

[当用户键入'0','1'或'2'时,将打印“ Hey You”。但是,当用户键入任何字母(例如“ y”或“ k”)时,也会打印“ Hey You”。如何确保仅对小于3(即y)的值打印“ Hey You”。

c scanf atoi
1个回答
0
投票

您在哪里定义input?您是否已经为要存储的字符串分配了内存?否则,您可能会遇到细分错误,或者atoi可能返回0

根据atoihttps://en.cppreference.com/w/cpp/string/byte/atoi)的文档,如果字符串中包含多余的非数字符号,它将忽略它们,如果没有,则返回0

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