c - 丢弃 C 中的字符?

标签 c

我正在介绍 C,我需要编写一个程序来提示用户输入字符、等号和整数。我需要使用 getchar() 直到 '=' 然后使用 scanf() 获取整数。然后程序应该只输出整数返回给用户。

现在它打印出不必要的代码重新输入每个字符的位置,然后在最后输出正确的整数。这是我的代码:

#include <stdio.h> 
#define EQUAL '=' 
int main(void)
{ 
    char ch;
    int integer = 0;

    printf("Enter some text, an equal sign and an integer:\n");
    while ((ch = getchar())!= '\n') //while not end of line
    {
        if (ch == EQUAL){
            scanf("%d", &integer);
        }
        printf("The integer you entered is: %d\n", integer);
    }

return 0;  
}  

我找不到示例,需要说明如何解决问题。

最佳答案

你被 C 中的陷阱咬住了。问题是这样的:

if( ch == EQUAL )
    scanf("%d", &integer);
    printf("The integer you entered is %d\n", integer);
没有大括号的

if 将只包含它后面的单个语句。该代码实际上是这样的:

if( ch == EQUAL ) {
    scanf("%d", &integer);
}
printf("The integer you entered is %d\n", integer);

为了避免这个陷阱,我会推荐两件事:

  • 始终正确缩进您的代码。
  • 切勿在没有大括号的情况下使用 if、else 或 while。

gcc 支持关于此的警告,-Wmisleading-indentation

如需了解更多此类问题,请阅读 "C Traps And Pitaflls" Andrew Koenig 着。

关于c - 丢弃 C 中的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33642986/

相关文章:

c - Travis CI 使用非 perl 语言安装 perl 模块

c++ - 未找到符号又名 undefined symbol

c - 初始化结构时出现段错误

c - 在我的读取函数 myread 中,当我执行 cat/driver/mydriver 时,它会不断打印读取的数据。我只需要打印一次如何做到这一点

c - 通过信号 SIGQUIT 唤醒 sleep 守护进程

c - 查找最小整数的函数 (C)

c - 如何在内核模块的相同偏移量中预留内存

c - 向字符串添加 header 并使用 TCP 套接字发送

php - 在某些情况下无法从 PHP 停止 C 守护进程

c - 编译包含<math.h>的c代码时需要使用额外的选项