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

标签 c scanf getchar

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

#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/

相关文章:

常量与静态常量

C/C++ printf() 在 scanf() 问题之前

无法读取所有字符串

c - getchar() 不返回或继续

c - 在 while 循环中输入 key

复制用户的输入并将其显示在屏幕上

c - 使用 char[] 获取可变大小的 C 可变参数

c - Julia - 具有 struct hack 的 C 类型会导致段错误

c - 为什么 STM32 gcc 链接器脚本会自动丢弃这些标准库 : libc. a、libm.a、libgcc.a 中的所有输入节?

c - 尝试扫描字符串时如何修复段错误?