Scan multiple integers without knowing the actual number of integers
I need to enter values whose frequency I do not know ...
For example, the first input: 1 32 54 65 6
second entrance: 2 4 5
What I thought at first was scans for values, if a newline '\ n' then breaks the loop, but that's not that good, so instead I said I use characters, then I come to type to get the number, but the problem is with this also was that it scans one character per unit, and if its negative value is also a problem,
Something like that
#include <stdio.h>
int main(){
int myarray[20];
int i=0, data;
while(1){
scanf("%d", &data);
if (data == '\n') break;
myarray[i]=data;
}
return 0;
}
but then scanf jumps over all special characters and only looks for ints ... is there a way to scan ints into an array and when there is a newline does it stop?
source to share
My advice, go for fgets()
.
- Read everything
line
from the entrance - Tokenize using space [
] [or your preferred separator] [usingstrtok()
] - Allocate memory to store an integer
- Convert string input to integer [possibly
strtol()
] and store each integer.
Optionally, you can add error checking and error checking.
Read more about fgets()
here .
also don't forget to get rid of the final \n
stored in the read buffer withfgets()
source to share
Recommend using fgets()
as suggested by Sourav Ghosh
Otherwise, the code can search '\n'
before reading eachint
#include <ctype.h>
#include <stdio.h>
#define N (20)
int main(void) {
int myarray[N];
int i = 0;
while (1) {
int ch;
while (isspace(ch = fgetc(stdin)) && ch != '\n')
;
if (ch == '\n' || ch == EOF)
break;
ungetc(ch, stdin);
int data;
if (scanf("%d", &data) != 1)
break; // Bad data
if (i < N)
myarray[i++] = data;
}
return 0;
}
source to share