gpt4 book ai didi

c - 丢弃 C 中的字符?

转载 作者:太空宇宙 更新时间:2023-11-04 07:05:17 30 4
gpt4 key购买 nike

我正在介绍 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com