Note that there are some explanatory texts on larger screens.

plurals
  1. POUnexpected results with multiple spaces using fgets
    text
    copied!<p>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.</p> <p>Why is this happening?</p> <p>How can I fix this?</p> <pre><code>#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; } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload