Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read numbers from the console given in a single line, separated by a space

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.

like image 992
tabula Avatar asked Jan 21 '15 14:01

tabula


People also ask

How to get input separated by space in c?

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.

How is input space-separated?

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 to separate input numbers in c?

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.


1 Answers

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.

like image 110
Tim Schmelter Avatar answered Sep 22 '22 01:09

Tim Schmelter