【问题标题】:scanf() in loop with a conditional does not work带有条件的循环中的scanf()不起作用
【发布时间】: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", &amp;input, &amp;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' &amp;&amp; type != 'd' &amp;&amp; type != 'i')
  • 关于:sum = (sizeof(input)) + sum; 变量 input 是一个 int,它总是(取决于底层硬件架构)4 或 8

标签: c loops if-statement scanf sizeof


【解决方案1】:

替换

if(type != 'c' || type != 'd' || type != 'i')

由

if(type != 'c' && type != 'd' && type != 'i')

【讨论】:

  • 我很好奇为什么在这种情况下使用 && 运算符?如果我想 ||是问它会是“如果类型不是'c' OR 'd' OR 'i' 那么......并使用&&我在想AND,所以用“AND”切换“OR”将意味着所有必须满足 3 个条件,这似乎不直观
  • 如果“type”等于“c”,那么type != 'd' 等于“true”。所以整个条件都是真的。在 Java 中,您得到完全相同的结果……是的,“必须满足所有 3 个条件”
  • @KatieMelosto -- 您感兴趣的案例是“NOT ('c' OR 'd' OR 'i')”,在逻辑上等同于“NOT 'c' AND NOT 'd ' 而不是 '我'";见De Morgan's Laws。
猜你喜欢
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 2012-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
相关资源
最近更新 更多