Objective c 使用FGET的多个空间出现意外结果

Objective c 使用FGET的多个空间出现意外结果,objective-c,nsstring,fgets,Objective C,Nsstring,Fgets,在我的程序中,我需要用户能够通过命令行命名“豌豆植物”。 我使用的是fgets,由于我不希望名称中允许有空格,所以我设置了一个while循环,通过rangeOfString生成字符串中有空格的任何名称条目。 这几乎在所有时间都有效——当用户键入一个没有空格的字符串时,它会让它通过,当用户键入一个空格或多个空格时,它通常会阻止他们。 但是,我发现两个字符串会产生意外的结果: “nyan nyan cat cat”(引号实际上没有输入)在一行中给出两个正确的错误报告,而您只输入一次。 “Isa pe

在我的程序中,我需要用户能够通过命令行命名“豌豆植物”。 我使用的是fgets,由于我不希望名称中允许有空格,所以我设置了一个while循环,通过rangeOfString生成字符串中有空格的任何名称条目。 这几乎在所有时间都有效——当用户键入一个没有空格的字符串时,它会让它通过,当用户键入一个空格或多个空格时,它通常会阻止他们。 但是,我发现两个字符串会产生意外的结果: “nyan nyan cat cat”(引号实际上没有输入)在一行中给出两个正确的错误报告,而您只输入一次。 “Isa pea plant”发出一次正确的错误报告,然后让最后两个字母“nt”通过

为什么会这样

我怎样才能解决这个问题

#import "Pea.h"

int main (int agrc, char * argv[])

{
    @autoreleasepool {
        int numb1 = 1;
     Pea *pea1 = [[Pea alloc] init];    char word1[13];
while( numb1 == 1) {
NSLog(@"What would you like to name this pea?");
fgets(word1, 13, stdin);
size_t length1 = strlen(word1);
if(word1 [length1-1] == '\n') // In case that the input string has 12 characters plus '\n'
    word1 [length1-1] = '\0'; // Plus '\0', the '\n' isn't added and the if condition is false.
NSString* userInput1 = [NSString stringWithUTF8String: word1];
[pea1 setName: userInput1];
//Makes sure string contains no spaces (spaces cause an error, and if I were to allow them in the name it would be easier in the future to forge messages out of a plant name.)
if ([pea1.name rangeOfString:@" " ].location == NSNotFound) {
    NSLog(@"The pea plant has been successfully named %@", [pea1 name]);
    numb1 = 0;
}
else {
    NSLog(@"The pea plant has not been named because you have included a space in it!");
    numb1 = 1;
}
}

如果要避免在输入中使用空格,为什么不在输入中没有空格的情况下只设置“Pea”对象的名称

例如:

NSString* userInput1 = [NSString stringWithUTF8String: word1];
//Makes sure string contains no spaces (spaces cause an error, and if I were to allow them in the name it would be easier in the future to forge messages out of a plant name.)
if ([userInput1 rangeOfString:@" " ].location == NSNotFound) {
    [pea1 setName: userInput1];
    NSLog(@"The pea plant has been successfully named %@", [pea1 name]);
    numb1 = 0;
}
else {
    NSLog(@"The pea plant has not been named because you have included a space in it!");
    numb1 = 1;
}