[英]How do I count the number of words if the user enters multiple lines/spaces?
[英]How do I read user input across multiple lines, spaces etc?
我试图扫描一些用户输入,但是当我运行程序时,我得到的只是一堆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';
}
为了更好地控制用户输入,您可以使用getchar()逐字符读取用户输入,通常在用户输入CTRL-D时它将返回EOF。 此后,可以解析字符串以提取输入的分数等。
如果您仍想使用诸如scanf()之类的方法,则可以考虑将其替换为对fgets()的调用,以防止缓冲区溢出。 或将scanf()与适当的格式字符串 ( 指定的最大字符数 )一起使用。
/* gcc -o test_getchar test_getchar.c && ./test_getchar */
#include <stdio.h>
int main()
{
char user_input[1000] = {0};
int i = 0;
char c;
while ((c = getchar()) != EOF) {
/* do something with c here... */
user_input[i] = c;
++i;
if (i >= sizeof(user_input)-1)
break;
}
user_input[i] = 0;
printf("user input: %s\r\n", user_input);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.