gpt4 book ai didi

c - 读取字符数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:14 26 4
gpt4 key购买 nike

我用 C 编写了一个读取字符数组的程序。它没有正常工作。

#include <stdio.h>

int main()
{
char a[50];
int n, i;
scanf("%d", &n);
for(i=0; i<n; i++)
scanf("%c", a+i);
for(i=0; i<n; i++)
printf("%c ", *(a+i));
return 0;
}

这个程序没有读出我想要的字符。

输入

5
a b c d e

程序打印

 a   b   

当我将 scanf("%c", a+i) 更改为 scanf("%c", a+i) 时,它工作正常。

有人能解释一下为什么第一个代码没有按我想要的那样工作吗?

最佳答案

scanf("%c", a+i); 没有工作,因为它消耗了前一个 scanf< 中留在 stdin 缓冲区中的换行符 调用。 scanf 的格式字符串中的 %c 转换说明符匹配一个字符,并且通常跳过前导空格被抑制。当你在 scanf

的格式字符串中添加一个前导空格时
scanf(" %c", a + i);
// ^ note the leading space

表示 scanf 将读取并丢弃任意数量的前导空白字符。因此它适用于您的情况。

关于c - 读取字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22920813/

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