c - 简单的for循环无限运行

标签 c for-loop

我是 C 的新手,我需要帮助来完成这个使用 for 的简单练习。我需要从用户那里得到一个 char 和一个 int 值。然后我必须打印 char 与之前输入的 int 一样多的次数。

这是我的:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char a;
    printf("Enter a character:");
    scanf(" %c", &a);
    int n;
    printf("Enter a number:");
    scanf(" %c", &n);
    printf("\n");

    int x;
    for(x=0; x < n; x++){
        printf(" %c", a);
    }
    return 0;
}

我的问题是它在 for 中形成无限循环。

我需要你的帮助。

谢谢

最佳答案

这里,n 是一个int,而不是一个char。因此,您需要使用 %d 来阅读它。在此处使用 %c 将导致未定义的行为。根据 “C99 – ISO 9899-1999”:

§7.19.6.2 The fscanf function1

[...] If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.

改变

scanf(" %c", &n);

scanf(" %d", &n);

查看 here了解更多信息。


<子> 1:scanf 函数等同于插入参数 stdinfscanfscanf 的参数之前。

关于c - 简单的for循环无限运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23273976/

相关文章:

python - 将列表中的项目映射到列表列表

c - 使用 sscanf 将带有括号和逗号的字符串拆分为更小的变量

c - 无锁算法库

java - 具有用户输入的二维数组

c - 如何创建 C 程序来确定输入值的最大值?

Javascript 过滤数组中的元素,该数组将另一个数组中的元素保存在一起

python - Append 函数无法退出 for 循环

C:关于指针使用的困惑

c - 如果我运行同一个程序两次,哪一部分内存将被共享

c - 从C中的逗号分隔文本文件中读取各种长度的数据