I am a math teacher and I am learning the very basics of C programming. I need a program to read input, consisting of an array whose components must have certain details; I would like the program to ask the user for the array components. Then the user needs to enter such components, separating them with spaces. Details are not important to get the main question; I will choose a simpler example than the one I'm dealing with: let me want the array with 6 components to not contain the number 4. So I tried:
#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]); } }
If I compile this and run it and, for example, type:
1 2 3 4 5 6
I will get my error message, but only after pressing enter, that is, after entering all six components (not immediately after you press the space bar for the fourth time). So here are my questions (I'm looking for solutions that don't use strings or pointers if it is impossible to do without them):
Is there a way to make the program read the component (and act accordingly) immediately after its subsequent space has been introduced? I suppose not, because scanf only works after the user presses enter, not a space, right?
If this does not happen, is there a way to get the program to read the components immediately after pressing input at the end, but let the user pick up the last 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 entry (possibly also changing the first three digits).
Sorry if this question is too dumb! Thank you for your help!
EDIT: Well, thanks for the great answers, you were all very helpful! I wish I could take more than one.
source share