c - 如何跨多行、多空格等读取用户输入?
问题描述
我正在尝试扫描一些用户输入,但是当我运行程序时,我得到的只是一堆 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++;
}
解决方案
你的代码没问题。以下程序:
#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';
}
推荐阅读
- asp.net-mvc - 实体框架更新数据库记录
- powershell - VS Code - How do I customize the theme colors of PowerShell
- svg - SVG 具有来自屏幕阅读器标题属性的文本减速器出现在视野中
- sql - 在 SQL 事实表中索引连接的外键字段?
- docker - NextCloud Docker 文件上传不工作错误 504?
- sql-server - WHERE 子句中的 SQL 子查询导致错误
- c - 此客户端-服务器迷你游戏不会自行重启
- python - HDF5 Python - 处理来自多个进程的读取的正确方法?
- c# - 如何使用正在运行我的 Windows App Store 应用程序的 C# 获取当前目录?
- python - 我的 (x, 12, 370, 235, 3) 数据集的图像数据生成器