Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accepting any number of inputs from scanf function

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

int a[100];
int i = 0;

while((scanf("%d", &a[i])) != '\n')
 i++;

// Next part of the code

But this function is not going to next part of the code, seems like there is an infinite while loop.

How Do I solve this logical error? Is there any other alternatives to scanf like sscanf to read integers into an array?

like image 621
user2147954 Avatar asked Mar 08 '13 10:03

user2147954


People also ask

Can scanf take multiple inputs?

Inputting Multiple ValuesIf you have multiple format specifiers within the string argument of scanf, you can input multiple values. All you need to do is to separate each format specifier with a DELIMITER - a string that separates variables.

How do I scanf a number?

scanf("%d", &b); The program will read in an integer value that the user enters on the keyboard (%d is for integers, as is printf, so b must be declared as an int) and place that value into b. The scanf function uses the same placeholders as printf: int uses %d.

What is scanf () function?

The scanf() function reads data from the standard input stream stdin into the locations given by each entry in argument-list. Each argument must be a pointer to a variable with a type that corresponds to a type specifier in format-string.


2 Answers

scanf returns the number of input items that have been successfully matched and assigned, thus it is reasonable to do:

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

Now you want to be able to read multiple numbers, each defined on the new line. Then you could simply do this:

int array[100];
int i = 0;

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

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

like image 67
LihO Avatar answered Nov 09 '22 17:11

LihO


The return value of scanf is the number of input items successfully matched and assigned, so try this to end when a non-numeric input is encountered:

while (i < 100 && (scanf("%d", &a[i])) == 1) { i++; }
like image 26
Klas Lindbäck Avatar answered Nov 09 '22 15:11

Klas Lindbäck