Ashish Agarwal Ashish Agarwal - 2 months ago 9
Objective-C Question

Input a string from console using Objective C

I am trying to enter a string (or a number of integers) from the command line using Objective C. These numbers are separated by a space.

Sample Input: 1 2 3 4 5

I am trying the code

char input[100] = {0};
NSString *inputString;
scanf("%s", input);
inputString = [NSString stringWithCString:input encoding:NSUTF8StringEncoding];

The resulting value of
is 1.

How do I get the entire value into the string ?


When you use %s in scanf it truncate the input at the first space. See here:

Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.

You can use this according to this source:

scanf("%[^\n]s", intpu);

You can also use gets() as an alternative.