【问题标题】:Program is running well when use int but when I use char it starts skipping line使用 int 时程序运行良好,但是当我使用 char 时它开始跳行
【发布时间】:2022-01-10 13:43:09
【问题描述】:

我是 c 编码的新手,我的程序在使用 int 数据类型时运行良好,但是当我使用 char 时它开始跳行。

#include <stdio.h>

int main() {
    int i;
    char k[10];
    for (i = 0; i < 10; i++) {
        printf("enter your character for line %d: \n", i);
        scanf("%c", &k[i]);
    }
    for (i = 0; i < 10; i++) {
        printf("your character for line %d are %c \n", i, k[i]);
    }

    return 0;
}

【问题讨论】:

  • 众星云集?

标签: arrays c char scanf


【解决方案1】:

好吧,当您按下 Enter 时,您正在向程序的输入中写入“换行”字符。
而且因为它是角色,%c 正在阅读它。

说明符%c 不像其他说明符那样占用空格,因此您必须通过在%c 之前添加空格来明确告诉scanf 跳过空格,这样您就可以使用" %c" 作为格式。

更多详情可能在这里:
https://stackoverflow.com/a/5240807/2416941

编辑:请注意,这样您无法从用户输入中读取空格或制表符。

【讨论】:

    猜你喜欢
    • 2019-11-22
    • 2013-07-27
    • 2017-12-19
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多