Search code examples
objective-cconsole-applicationfgets

Fgets isn't getting any input from stdin or stdin isn't being equaled to the input?


Example code:

    char cnumb1[2];
    NSLog(@"Do you have an account already?(1 for Yes, 0 for no)");
    int c;
    //Flushes input
    while((c = getchar()) != '\n' && c != EOF);
    fgets(cnumb1, sizeof cnumb1, stdin);
    size_t length = strlen(cnumb1);
    if (cnumb1 [length-1] == '\n'){ // In case that the input string has 1 character plus '\n'
        cnumb1 [length-1] = '\0';} // Plus '\0', the '\n' isn't added and the if condition is false.
    NSString* string = [NSString stringWithUTF8String: cnumb1];
    NSLog(@"string:%@", string);

With the input "0" (EDIT: For some reason, I need to press enter twice), I get the output "string:" As far as I can tell, the stdin isn't being set correctly. Also, the I started without the flush lines, but that caused lots of problems because I have more fgets later on and it the stdin would only be the initial input, so I added those.

Why isn't the input being set as stdin? Or is it another problem entirely?


Solution

  • The line

    while((c = get char()) != '\n' && c != EOF);
    

    needs to go directly AFTER the fgets, not before.

    Also, while not answering the question directly, its better to do

    fgets(cnumb1, sizeof cnumb1, stdin);
    

    then hardcode in the sizeof cnumb1, as @H2CO3 kindly pointed out to me.