Accepting any number of inputs from the scanf function

I am trying to read an unknown number of inputs using the scanf function.

 int a[100]; int i = 0; while((scanf("%d", &a[i])) != '\n') i++; // Next part of the code 

But this function does not go to the next part of the code, it seems that there is an infinite while loop.

How to solve this logical error? Are there other alternatives to scanf like sscanf for reading integers into an array?

+4
source share
5 answers

scanf returns the number of input elements that were successfully mapped and assigned, so it’s wise to do:

 while(scanf(...) == 1) 

Now you want to be able to read several numbers, each of which is defined in a new line. Then you can simply do this:

 int array[100]; int i = 0; while(i < 100 && scanf("%d\n", &array[i]) == 1) i++; 

note that this reading will be stopped only when entering invalid input (for example, letter q ) or when entering the end-of-code control code, which is Ctrl + Z (on Windows) or Ctrl + D (on Mac, Linux, Unix).

+8
source

The return value of scanf is the number of input elements that are successfully matched and assigned, so try completing this when non-numeric input is encountered:

 while (i < 100 && (scanf("%d", &a[i])) == 1) { i++; } 
+2
source

You want to do

 char discard; while(i < 100 && (scanf("%d%1[^\n]s", &arr[i], &discard)) == 2) i++; 

to continue to enter information until a new line.

scanf () is not the best tool to read whole lines. You should use fgets () to read the string and then parse it with sscanf () or other functions.

0
source

The return value of scanf is the number of scanned inputs per call. You can compare it with an integer of 10 (or '\ n'), which will stop the loop when scanf actually reads 10 elements. (And for this, there should have been ten qualifiers in the format string.

You can try

  while((i<10) && (scanf("%d",a+i)==1)) i++; 

You need to program any number of arguments, for example. a

  while (fgets(mybuf, ALLOCATED_LENGTH-1, stdin)) { char *p = mybuf; if (*p=='\n') break; // or a better function to test for empty line while (custom_scan_next_integer(&p)) i++; } 

where custom_scan_next_integer changes the p pointer to forward the correct number of characters.

0
source

First replace "%d" with " %d" , this will avoid problems with a new line

second, if your input contains non-numerical input, then your while loop will go into an infinite loop. so you need to check your input if it contains numerical input

0
source

All Articles