c - for循环中的数字不增加

标签 c

<分区>

我的任务是扫描 10 个数字,这些数字稍后会被转换成字符。问题是,如果我不输入 0,我不明白为什么会出现无限循环。我使用数组正确地完成了任务,但我很感兴趣为什么会在下面的示例中发生这种情况。

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

int main() {
/**
* for the example enter numbers: 8 5 12 12 15 23 15 18 12 4 -> helloworld
*/
    char n;
    // message needs to be 10 numbers long.
    for (int i = 1; i <= 10; i++){
      // enter message in numbers.
        scanf("%d", &n);
        // check if it is 0. if it is, end the message.
        if(n == 0) {
            printf("\nEnd of the message!");
            break;
        // if number is not 0, add 64 to transform to char.
        }else {
            n = n + 64;
            // print the char.
            printf("%c ", n);
            // print the i, that doesn't increment.
            printf(" -> i:%d\n", i);
        }
    }
    return 0;
}

最佳答案

您正在使用

char n;
...
scanf("%d", &n);

您不能将 %dchar 一起使用。您应该将 n 更改为 int 或将 %c 用于 scanfprintf .

int n;
...
scanf("%d", &n);

char n;
...
scanf("%c", &n);

关于c - for循环中的数字不增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52924357/

相关文章:

c - strstr 匹配 c 中的第一次出现

c、数组和malloc的区别。错误

c - 读取和保存未知长度字符串的已知行数

c - 在 C 中访问指针的指令有多少?

c - 对文件进行快速排序

c - 在 C 文件中使用 float4

java - 错误 : conflicting types using C in Android ndk

c - 当函数体没有返回语句时内联

c - C中的反向字符串输出不正确

C LINUX\WINSOCK-检查Send中的FIN包