Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read numbers separated by space using scanf

I want to read numbers(integer type) separated by spaces using scanf() function. I have read the following:

  • C, reading multiple numbers from single input line (scanf?)
  • how to read scanf with spaces

It doesn't help me much.

How can I read numbers with space as delimiter. For e.g. I have following numbers as input 2 5 7 4 3 8 18 now I want to store these in different variables. Please help.

like image 559
Jainendra Avatar asked May 03 '12 06:05

Jainendra


People also ask

How do you read input separated by space?

There are 2 methods to take input from the user which are separated by space which are as follows: Using BufferedReader Class and then splitting and parsing each value. Using nextInt( ) method of Scanner class.

How do I make scanf read whitespace?

So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);

How does scanf work with spaces?

Adding a whitespace character in a scanf() function causes it to read elements and ignore all the whitespaces as much as it can and search for a non-whitespace character to proceed. scanf("%d "); scanf(" %d"); scanf("%d\n"); This is different from scanf("%d"); function.

Does scanf read spaces in C?

The scanf() function can read input from keyboard and stores them according to the given format specifier. It reads the input till encountering a whitespace, newline or EOF.


2 Answers

I think by default values read by scanf with space/enter. Well you can provide space between '%d' if you are printing integers. Also same for other cases.

scanf("%d %d %d", &var1, &var2, &var3); 

Similarly if you want to read comma separated values use :

scanf("%d,%d,%d", &var1, &var2, &var3); 
like image 151
Nandkumar Tekale Avatar answered Sep 28 '22 01:09

Nandkumar Tekale


scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.

Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.

like image 37
Chris Dodd Avatar answered Sep 28 '22 01:09

Chris Dodd