i want to read space separated integer into an array and when i press enter it should stop reading at any point of time, how to implement loop for this prog
scanf("%d"...
first begins by consuming leading white space. To detect '\n'
, code should scan leading white-space before calling scanf("%d"...
.
To terminate input when a '\n'
occurs, first begin looking for it. Suggest using getchar()
.
The following code handles OP goals and:
* Lines beginning with \n
* Lines with more than N int
* EOF and non-numeric input
#include
#include
#define N (30)
int main(void) {
int arr[N];
int j = 0;
for (j = 0; j < N; j++) { // Don't read too many
int ch;
while ((ch = getchar()) != '\n' && isspace(ch));
if (ch == '\n') {
break;
}
// put back ch
ungetc(ch, stdin);
int cnt = scanf("%d", &arr[j]);
if (cnt != 1) {
break; // Stop if input is EOF or non-numeric
}
}
printf("%d\n", j);
return 0;
}