user3564573
user3564573

Reputation: 700

Scan multiple integers without knowing the actual number of integers

I have to input values whose frequency i don't know...

For example first input: 1 32 54 65 6

second input: 2 4 5

What i first thought was, scan the values, if new line '\n' then break the loop, but that didn't go so well, so instead i said i use characters, then i typecast to get the number but the problem with this also came that it scan one character by one and if its its a negative value its also a problem;

Something like this

#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 all the special characters and look for only ints... is there a way to scan ints to an array and when there is a newline it stops?

Upvotes: 4

Views: 2361

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134346

My advice, go for fgets().

  1. Read the whole line from the input
  2. Tokenize using space [] [or your preferred delimiter] [using strtok()]
  3. Allocate memory to store the integer
  4. Convert the string input to integer [maybe strtol()] and store each integer.

Optionally, you may want to add some validation and error checking.

Read more about fgets() here.

also, don't forget to get rid of the trailing \n stored in the read buffer by fgets()

Upvotes: 6

chux
chux

Reputation: 153630

Recommend using fgets() as suggested by Sourav Ghosh

Otherwise code can search for '\n' before reading each int

#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;
}

Upvotes: 0

Related Questions