【发布时间】:2020-04-16 21:30:24
【问题描述】:
我正在制作一个返回用户输入大小总和的简单程序。 用户首先输入一个 int 来表示要添加的 sizeof() 总和 后跟数据类型的输入和字符。 这一切都行得通,但是,如果用户输入除“c”、“d”或“i”以外的任何内容循环中断并打印“无效的跟踪代码类型”,则会失败。
我的程序在条件下失败 - 即使 scanf() 正确获取了字符,它仍然失败。
举例:
输入:
3
10 i
7 c
12 d
输出
143 bytes
输入
1
1 o
输出
invalid tracking code type
如何在循环中使用 scanf 比较用户输入?
#include <stdio.h>
int main()
{
int num, input, i, sum;
int invalid = 1;
sum = 0;
i = 0;
char type;
printf("give me a num!\n");
scanf("%d", &num);
while(i < num)
{
printf("int and char?\n");
//scanf("%d", &input);
//scanf(" %c\n", &type);
if (scanf("%d %c", &input, &type) != 2)
{
printf("TYPE IS: %c\n", type);
}
printf("TYPE IS: %c\n", type);
if(type != 'c' || type != 'd' || type != 'i')
{
printf("invalid tracking code type");
invalid = 0;
break;
}
i++;
//printf("what is i? %d\n", i);
sum = (sizeof(input)) + sum;
printf("IT's the sum %d\n", sum);
}
if(invalid != 0)
{
printf("%d bytes", sum);
}
return 0;
}
还有许多其他 posts 回答了类似的问题,但找不到专门针对此问题的任何内容。
我尝试了很多方法,例如分离 scanf(),对条件使用不同类型的运算符。没有条件它可以正常工作,但有条件它总是返回“无效的跟踪代码类型”,即使它们是正确的。
【问题讨论】:
-
type != 'c' || type != 'd' || type != 'i'永远为真。 -
对
scanf返回值的检查也是奇怪的。您实际上似乎忽略了它,因为您打印了如果返回值是 `!= 2` 肯定不会设置的变量的值。 -
关于:
if (scanf("%d %c", &input, &type) != 2) { printf("TYPE IS: %c\n", type); }对printf()的调用应该是对fprintf( stderr, "some error message\n");的调用 -
关于:
if(type != 'c' || type != 'd' || type != 'i')这不是正确的逻辑。建议:if(type != 'c' && type != 'd' && type != 'i') -
关于:
sum = (sizeof(input)) + sum;变量input是一个int,它总是(取决于底层硬件架构)4 或 8
标签: c loops if-statement scanf sizeof