首页 > 解决方案 > 如何跨多行、多空格等读取用户输入?

问题描述

我正在尝试扫描一些用户输入,但是当我运行程序时,我得到的只是一堆 3/4 分数。

我需要能够扫描字符、空格和换行符。如果用户输入如下内容:

Hello this
  is
     a test123 234     !!!

一旦他们完成输入他们想要输入的内容,他们将按 CTRL+D,这就是我知道停止阅读他们所说的内容的方式。

这是我的代码:

char user_input[1000];
int i = 0;
    while (scanf("%c", &user_input[i]) == 1) {
        i++;
}

标签: carrayswhile-loopcharscanf

解决方案


你的代码没问题。以下程序:

#include <stdio.h>

int main()
{
    char user_input[1000];
    int i = 0;
    while (scanf("%c", &user_input[i]) == 1) {
        i++;
    }
    user_input[i] = '\0';
    printf("%d\n", i);
    printf("%s", user_input);
    return 0;
}

使用您的输入生成以下内容:

42
Hello this
  is
     a test123 234     !!!

不过scanf一般是用来scan formatted输入的。getchar()我建议使用或一次读取一个字符fgets()

int main(void) {
   char user_input[1000];
   int i = 0;
   int temp;
   while ((temp = getchar()) != EOF) {
        user_input[++i] = temp;
   }
   user_input[i] = '\0';
}

推荐阅读