我正在编写一个简单的程序,返回用户输入大小的总和。用户首先输入一个int表示sizeof()的总和后面跟一个输入和char作为数据类型。但是,所有这一切都有效,但失败的是,如果用户键入除“ 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()。在没有条件的情况下,它可以正常工作,但在有条件的情况下,即使它们正确,也始终会返回“无效的跟踪代码类型”。
替换
if(type != 'c' || type != 'd' || type != 'i')
由
if(type != 'c' && type != 'd' && type != 'i')