Ios 如何在Objective-C中从char数组转换为NSString
我试图从用户处读取类型为Ios 如何在Objective-C中从char数组转换为NSString,ios,objective-c,xcode,nsstring,Ios,Objective C,Xcode,Nsstring,我试图从用户处读取类型为NSString的输入,但找不到NSString的格式说明符,我知道%I用于整数变量,但哪个用于NSString 结果,我创建了一个char数组,读取用户的输入,但我无法将其转换为NSString,XCode将一些奇怪的东西作为输出,比如øÿ,有时(null),我使用了许多字符串编码,比如(它们都不起作用): 谁能告诉我为什么? 这是我的代码: //I have declared a class and called it Labtop Labtop *myLabto
NSString
的输入,但找不到NSString
的格式说明符,我知道%I
用于整数变量,但哪个用于NSString
结果,我创建了一个char数组,读取用户的输入,但我无法将其转换为NSString
,XCode将一些奇怪的东西作为输出,比如øÿ
,有时(null)
,我使用了许多字符串编码,比如(它们都不起作用):
谁能告诉我为什么?
这是我的代码:
//I have declared a class and called it Labtop
Labtop *myLabtop;
myLabtop = [[Labtop alloc] init];
char input[30];
NSLog(@"Hello,please enter which brand you will use this time:\n");
input[29] = getchar();// read the input from the user
NSString *b =[[NSString alloc] initWithCString:input encoding:NSISOLatin1StringEncoding];//convert from array char to NSString
[myLabtop labtopBrand:b];//labtopBrand fund will print what the user has entered
结果是:
您好,请输入您此次使用的品牌:
MacBook//这是用户的输入
我将使用øÿ//这是Xcode显示给我的输出程序
退出代码为:0
NSString的格式说明符为%@此处存在一些问题。首先,
getchar()
返回一个字符,而不是整个字符串。第二,这一行:
input[29] = getchar();// read the input from the user
只需将input
中的最后一个字符指定给用户键入的字符,这可能根本不是您想要的。也许你的意思是get()
?除非你真的不应该使用它,因为它没有边界检查,你仍然不想把结果分配给数组中的第三十个字符。也许可以看看getline()
另外,您可能需要指定NSUTF8StringEncoding
祝你好运,继续尝试 您确定输入包含有用的内容吗?也许还没定下来?
input[29] = getchar();// read the input from the user