使用Objective C从控制台输入字符串

时间:2022-09-06 13:09:42

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.

我试图使用Objective C从命令行输入一个字符串(或一些整数)。这些数字用空格分隔。

Sample Input: 1 2 3 4 5

样本输入: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.

inputString的结果值为1。

How do I get the entire value into the string ?

如何将整个值放入字符串中?

2 个解决方案

#1


2  

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

在scanf中使用%s时,它会截断第一个空格处的输入。看这里:

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.

您也可以使用gets()作为替代方案。

#2


4  

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

在将目标C作为工作语言时,请更准确地尝试这一点

#1


2  

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

在scanf中使用%s时,它会截断第一个空格处的输入。看这里:

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.

您也可以使用gets()作为替代方案。

#2


4  

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

在将目标C作为工作语言时,请更准确地尝试这一点