gpt4 book ai didi

c - 我如何像 scanf() 一样使用 getchar()?

转载 作者:太空宇宙 更新时间:2023-11-04 04:38:16 25 4
gpt4 key购买 nike

我看到这个程序可以读取整个字符串:

#include <stdio.h>

int main(int argc, char *argv[]){
int something;
printf("Enter something \n");
while (scanf("%c", &something)==1) {
printf("%c", something);
}
return 0;
}

当我输入 hello world 时,它会输出 hello world

谁能解释一下为什么它不输出:

h
e
l
l
...

因为我认为循环一次遍历一个字母,所以我很困惑为什么它没有那样输出。现在,我尝试编写一个程序来使用 getchar 来做同样的事情:

#include <stdio.h>

int main()
{
char c;

printf("Enter character: ");
c = getchar();

printf("Character entered: ");
putchar(c);

return(0);
}

当我输入 hello world 时,这个程序只输出 h。我如何使用 getchar 来做与第一个程序相同的事情?还有,getchar和scanf有什么区别?

最佳答案

getchar() 一次接受一个字符输入。如果您希望它读取整个字符串或字符数组,您可以使用 while 循环for 循环 来逐个存储每个字符。例如:c[i]=getchar() for i = 0 to string length,或者while c[i]!='\n'

关于c - 我如何像 scanf() 一样使用 getchar()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29068517/

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