【问题标题】:Scanf() behaving odd for specific caseScanf() 在特定情况下表现奇怪
【发布时间】:2019-03-02 12:28:18
【问题描述】:

我有一些 C 代码可以接受 6 种不同格式的简单方程式(没有空格)

x + int = int
x - int = int
int + x = int
int - x = int
int + int = x
int - int = x

我正在使用 scanf 提取方程式中的数字,这适用于前 4 种情况,但不适用于后 2 种。我不知道为什么。

例如。对于前两种格式,我使用的是:

int digit1, digit2;
char operand;
if(scanf("x%c%d=%d", &operand, &digit1, &digit2) == 3) {
    if(operand == '+') {
        printf("x=%d", (digit2-digit1));
        exit(0);
    } else {
        printf("x=%d", (digit2+digit1));
        exit(0);
    }
}

这行得通。

对于最后两种格式,我使用的是这个(非常相似的)代码:

int digit1, digit2;
char operand;
if(scanf("%d%c%d=x", &digit1, &operand, &digit2) == 3) {
    if(operand == '+') {
        printf("x=%d", (digit1+digit2));
        exit(0);
    } else {
        printf("x=%d", (digit1-digit2));
        exit(0);
    }
}

由于某种原因,这不能按预期工作。

我尝试了一些不同的方法,发现 scanf() 跳过了第一个数字和数学运算符。这导致 if 语句不正确,因为现在 scanf() 只返回 2,因为它将 digit1 设置为第二个数字,将操作数设置为 '=' 符号,然后找不到更多的数字。

我的问题是为什么 scanf() 没有“看到”第一个数字。

对于这个示例输入

10+12=x

当前行为:

digit1 = 12
operand = '='
digit2 = 0

期望的行为:

digit1 = 10
operand = '+'
digit2 = 12

【问题讨论】:

  • 请完整代码 - 带有变量声明
  • 您的代码对于每种情况都是正确的。检查你如何组合它们。
  • %c 转换规范不跳过前导空格; %d 和大多数其他人(除了%[…] 扫描集和%n)都会跳过前导空格。您应该在格式中添加适当的空格,以允许输入中对应的零个或多个空格。不要使用 scanf() 格式的尾随空格。而你的12+13 显示
  • 我认为您最好阅读字符行(fgets() 或 POSIX getline()),然后使用 sscanf()(可能多次尝试)来解析字符串。这使您可以打印输入行,并更连贯地报告错误 - 并且通常使基于行的输入更轻松。

标签: c scanf equality


【解决方案1】:

由于第 3 和第 4 种情况的代码,我的代码被破坏了。

我通过组合案例 3 4 5 和 6 的代码来修复它。

if(scanf("%d%c", &digit1, &operator) == 2) {
    if(scanf("%d=x", &digit2) == 1) {
        if(operator == '+') {
            printf("x=%d", (digit1+digit2));
            exit(0);
        } else {
            printf("x=%d", (digit1-digit2));
            exit(0);
        }
    } else if(scanf("x=%d", &digit2) == 1) {
        if(operator == '+') {
            printf("x=%d", (digit2-digit1));
            exit(0);
        } else {
            printf("x=%d", (digit1-digit2));
            exit(0);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多