I want to read numbers(integer type) separated by spaces using scanf()
function. I have read the following:
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.
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.
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);
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With