0

在我的程序中,我需要用户能够通过命令行命名“豌豆植物”。我正在使用 fgets,并且由于我不希望名称中允许有空格,因此我设置了一个 while 循环,该循环通过 rangeOfString 生成在字符串中具有空格的任何名称条目。这几乎一直有效——当用户输入一个没有空格的字符串时,它会让它通过,而当他们输入一个空格或多个空格时,它通常会阻止它们。但是,我发现了两个给出意外结果的字符串:“nyan nyan cat cat”(实际上并未输入引号)在您只输入一次时连续给出两个正确的错误报告。“is a 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;
}
}
4

1 回答 1

0

如果您想避免输入中的空格,为什么不只在输入中没有空格的情况下设置“豌豆”对象的名称?

例如:

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;
}
于 2013-07-09T23:39:17.300 回答