Search code examples
objective-cnsstringfgets

Unexpected results with multiple spaces using fgets


In my program, I need users to be able to name a "pea plant" through the command line. I'm using fgets, and since I don't want spaces to be allowed in names, I set up a while loop that makes any name entries who have a space in the string through rangeOfString. This works almost all the time- when users type in a string without spaces it lets it pass, and when they type in a space or multiple spaces it usually stops them. However, I've found two strings that give unexpected results: "nyan nyan cat cat" (quotation marks aren't actually entered in) gives off two of the correct error reports in a row when you only enter it once. "is a pea plant" gives off the correct error report once, then lets the last two letters, "nt", pass.

Why is this happening?

How can I fix this?

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

Solution

  • If you want to avoid spaces in the input, why not only set the name of your "Pea" object if there's no space in the input?

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