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 ?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

to reduce number of lines i guess.... [[[NSString alloc] initWithData:[[NSFileHandle fileHandleWithStandardInput] availableData] encoding:NSUTF8StringEncoding] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
@KijitDesai sure makes more sense reducing the number of lines, works like a charm.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.