我是一名数学专业的学生,正在学习C语言的基础编程知识。我需要一个程序来读取由数组组成的输入,数组的组成部分必须满足一定的条件。我希望程序能够询问用户数组的组成部分。然后,用户应该输入这些组成部分,并用空格分隔它们。细节并不重要,重要的是让主要问题得到解决。下面我们来举个更简单的例子:假设我想要一个有6个元素的数组,但不希望出现数字4。那么我尝试了以下代码:
#include <stdio.h>
int main(void) {
int a[6];
printf("enter components: ");
int i;
for (i = 0; i < 6; i++) {
scanf("%d", &a[i]);
if (a[i] == 4) printf(" \n\n4 is not allowed, try again\n\n");
}
for (i = 0; i < 6; i++) {
printf("%d ", a[i]);
}
}
如果我编译并运行它,例如输入以下内容:
1 2 3 4 5 6
我会得到错误消息,但只有在按下回车键后才会出现,也就是在输入完所有六个组件之后(不是在第四次按空格后立即出现)。因此,以下是我的问题(我正在寻找不使用字符串或指针的解决方案,除非没有这样做的可能性):
Is there a way to get the program to read a component (and to act accordingly) straight after its subsequent space has been entered? I'm guessing there isn't because scanf only works after the user presses enter, and not space, correct?
If there isn't, is there a way to get the program to read the components all at once after having pressed enter at the end, but letting the user pick up from the last right component? For example, with the above input, I would like the program to display something like this:
4 is not allowed 1 2 3 _
so that the user can correct his/her input (possibly changing the first three digits as well).
抱歉如果这个问题太蠢了!谢谢你的帮助!
编辑:感谢众多热心回答,你们都非常有帮助!很遗憾我只能接受一个答案。