Ashish Agarwal
Ashish Agarwal

Reputation: 14925

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 inputString is 1.

How do I get the entire value into the string ?

Upvotes: 1

Views: 2318

Answers (2)

Nitish Makhija
Nitish Makhija

Reputation: 559

NSLog(@"Enter the string : ");
NSFileHandle *input = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [NSData dataWithData:[input availableData]];
NSString *inputString = [[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding];
inputString = [inputString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"%@", inputString);

Here try this more precise when talking objective C as the working language

Upvotes: 5

Merlevede
Merlevede

Reputation: 8170

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.

Upvotes: 3

Related Questions