I have a task to read n given numbers in a single line, separated by a space ( ) from the console.
I know how to do it when I read every number on a separate line (Console.ReadLine()) but I need help with how to do it when the numbers are on the same line.
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.
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.
Use a simple for loop. int i, n, arr[100]; scanf("%d", &n); for (i = 0; i < n; ++i) scanf("%d", &arr[i]); The above code snippet would do.
You can use String.Split. You can provide the character(s) that you want to use to split the string into multiple. If you provide none all white-spaces are assumed as split-characters(so new-line, tab etc):
string[] tokens = line.Split(); // all spaces, tab- and newline characters are used
or, if you want to use only spaces as delimiter:
string[] tokens = line.Split(' ');
If you want to parse them to int you can use Array.ConvertAll():
int[] numbers = Array.ConvertAll(tokens, int.Parse); // fails if the format is invalid
If you want to check if the format is valid use int.TryParse.
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