我有一个用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/