使用fgets的多个空格的意外结果

时间:2013-07-09 23:28:26

标签: objective-c nsstring fgets

在我的程序中,我需要用户能够通过命令行命名“豌豆工厂”。 我正在使用fgets,因为我不希望在名称中允许使用空格,所以我设置了一个while循环,它通过rangeOfString生成字符串中有空格的任何名称条目。 这几乎一直都在工作 - 当用户键入一个没有空格的字符串时,它会让它通过,当他们键入一个空格或多个空格时,它通常会停止它们。 但是,我发现两个字符串会产生意想不到的结果: 当您只输入一次时,“nyan nyan cat cat”(实际上没有输入引号)会连续发出两个正确的错误报告。 “是豌豆植物”发出一次正确的错误报告,然后让最后两个字母“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;
}
}

1 个答案:

答案 0 :(得分:0)

如果你想避免输入中的空格,为什么不设置输入中没有空格的“Pea”对象的名称?

E.G:

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;
}