私のプログラムでは、ユーザーがコマンドラインから「エンドウ豆」に名前を付けることができる必要があります。私は fgets を使用しています。名前にスペースを入れたくないので、rangeOfString を介して文字列にスペースを含む名前エントリを作成する while ループを設定しました。これはほぼ常に機能します。ユーザーがスペースなしで文字列を入力すると通過し、スペースまたは複数のスペースを入力すると通常は停止します。ただし、予期しない結果をもたらす 2 つの文字列を見つけました: "nyan nyan cat cat" (引用符は実際には入力されません) は、1 回だけ入力すると、2 つの正しいエラー レポートが連続して表示されます。「is a pea plant」は、正しいエラー レポートを 1 回出力した後、最後の 2 文字「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;
}
}