1

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 ?

Ashish Agarwal
  • 13,427
  • 30
  • 79
  • 122
  • possible duplicate of [Reading string from input with space character?](http://stackoverflow.com/questions/6282198/reading-string-from-input-with-space-character) – rmaddy Mar 13 '14 at 03:50

2 Answers2

5
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

Nitish Makhija
  • 548
  • 5
  • 20
  • to reduce number of lines i guess.... [[[NSString alloc] initWithData:[[NSFileHandle fileHandleWithStandardInput] availableData] encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]]; – Lycon Sep 10 '16 at 06:12
  • @KijitDesai sure makes more sense reducing the number of lines, works like a charm. – Nitish Makhija Sep 11 '16 at 07:59
3

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.

Merlevede
  • 7,946
  • 1
  • 22
  • 38