昨天刚开始用 Java 背景在 Objective-C 编程,我迷路了。我有一个可以运行的程序,它的目的是从控制台获取一个人的姓名、年龄和体重,然后将这些值输出给用户。我的问题是当我在控制台中输入数据时,它只会显示我输入的第一个字母。然后它不会显示我的字符串的任何其他字符。所以这里有一些示例控制台数据来证明我的观点。
安慰:
2012-11-14 17:56:05.673 Tutorial[1757:403] Please Enter In Your Name
warning: this program uses gets(), which is unsafe.
C
2012-11-14 17:56:09.494 Tutorial[1757:403] Please Enter Your Age
1
2012-11-14 17:56:11.239 Tutorial[1757:403] Please Enter Your Weight
2
2012-11-14 17:56:13.205 Tutorial[1757:403]
Name: Chris
Age: 18
Weight: 200
如您所见,它只会显示我输入的第一个字母,但它实际上使用输入字符串。为什么会发生这种情况?
函数声明:
#import "Person.h"
Person * readPersonData (Person * object);
void writePersonInformation(Person * object);
主要方法:
int main (int argc, const char * argv[])
{
@autoreleasepool
{
Person * p1 = [[Person alloc] init];
p1 = readPersonData(p1);
writePersonInformation(p1);
}
}
功能实现:
Person * readPersonData (Person * object)
{
char nameCharacters[100];
NSString * objectName;
int objectAge, objectWeight;
NSLog(@"Please Enter In Your Name");
gets(nameCharacters);
objectName = [[NSString alloc] initWithUTF8String:nameCharacters];
[object setName : objectName];
NSLog(@"Please Enter Your Age");
scanf("%i", &objectAge);
[object setAge : objectAge];
NSLog(@"Please Enter Your Weight");
scanf("%i", &objectWeight);
[object setWeight : objectWeight];
return object;
}
void writePersonInformation(Person * object)
{
NSLog(@"\nName: %@ \nAge: %i \nWeight: %i", object.getName, object.getAge, object.getWeight);
}