c - 为什么这会接受无效输入?

标签 c

我有一个用c编写的三角程序

#include <stdio.h>

// A function which decides the type of the triangle and prints it
void checkTriangle(int s1, int s2,int s3)
{
    // Check the values whether it is triangle or not.
    if ((s1 + s2 > s3 && s1 +  s3 > s2 && s2 + s3 > s1) && (s1 > 0 && s2 > 0 && s3 > 0))
    {
        // Deciding type of triangle according to given input.
        if (s1 == s2 && s2 == s3)
            printf("EQUILATERAL TRIANGLE");
        else if (s1 == s2 || s2 == s3 || s1 == s3)
            printf("ISOSCELES TRIANGLE\n");
        else
            printf("SCALENE TRIANGLE \n");
    }
    else
        printf("\nTriangle could not be formed.");
}

int main(void)
{
    // Initializing variables
    int a,b,c;

    // Getting input from user
    printf("Please enter the sides of triangle");

    printf("\nPlease enter side 1:");
    scanf("%d",&a);

    printf("Please enter side 2:");
    scanf("%d",&b);

    printf("Please enter side 3:");
    scanf("%d",&c);

    // Calling function in order to print type of the triangle.
    checkTriangle(a,b,c);
}

当输入是:

7b

它给出了一个错误,这正是我想要的,但是当我这样输入数据时:

7
7
7b 

它会忽略“b”并将 7 作为整数——但为什么呢?我怎样才能避免这种情况?

我想做的是也给错误

7
7
7b

最佳答案

如果您希望能够检测到用户输入的错误,例如一行不是有效的十进制整数,那么您可以执行以下操作:

  • 使用fgets(buffer, size, stdin)将输入读入缓冲区
  • 使用strtoul(buffer, &endptr, 10)将缓冲区解析为十进制整数(基数10),其中endptr是一个字符*
  • endptr 将指向 buffer 中的第一个无效字符,即。最后一个解析成功的字符之后的字符
  • 现在如果 *endptr == '\0',即。 endptr 指向buffer 的结尾,整个 字符串被解析为有效的十进制整数

关于c - 为什么这会接受无效输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12889612/

相关文章:

c - C的单元测试框架

c - 我想在使用写入功能时显示整数

c - Arduino伺服结构 "does not name a type"

c++ - Makefile 模式规则差异

c - 检测 COM 端口是否已关闭

c - 如何打印出 8 字节变量的所有 8 字节以及如何对它们应用 `&&` 位运算符?

c - 额外的 memset() 导致系统调用 open() 失败

c - 错误 : Expected expression before structure

c - 在c中将2个字符加在一起的问题

C: 不能在 if 语句中声明指针