it's skipping over my scanf?

Discussion in 'Mac Programming' started by larswik, Aug 12, 2010.

  1. larswik macrumors 68000

    Sep 8, 2006
    I'm learning still. I stripped this code out of a slightly larger one to find the problem. It seems so simple and yet I can't solve it. I have 3 'scanf' after 3 NSLog questions. The problem that I am having is that it skips over the second scanf and jumps right to the last one with no input from the user?

    Here is the code.
    #import <Foundation/Foundation.h>
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    	float tb, tb2;
    	char oper;
    	NSLog(@"Enter the first number:");
    	NSLog(@"Enter + or -");
    	NSLog(@"Enter the second number:");
        [pool drain];
        return 0;
    Help me ob one.

  2. larswik thread starter macrumors 68000

    Sep 8, 2006
    I found a work around from another site. It seems like after the first scanf it is storing something called a white space. The site recommended swapping the %c to %1s in the scanf. After doing this it worked fine.

    here is the link I got the info at.

  3. chown33 macrumors 604

    Aug 9, 2009
    Or tell scanf() to skip whitespace.

    You do this by providing a whitespace character, such as a single space, in the first input pattern. Example:
    	scanf("%f ",&tb);
    Note there is a single space between the 'f' and the closing quote of the string.

    You should read the scanf reference doc, paying particular attention to what it says about white space in the format string:
    White space (such as blanks, tabs, or newlines) in the format string match any amount of white space, including none, in the input.​
    This may seem strange, but it's completely standard scanf behavior.

    This is a disadvantage of using what seems like a simple function without completely understanding what it does. You get unexpected or even magical-seeming results.
  4. larswik thread starter macrumors 68000

    Sep 8, 2006
    Thanks for the information! I put it in and it worked for the that part and then it started pass over the last one. I will read over the links you included and see how much I understand.

    But if the %1s works, should I just keep using that?

    Thanks again!

  5. chown33 macrumors 604

    Aug 9, 2009
    Your choice.
  6. subsonix macrumors 68040

    Feb 2, 2008
    It's a classic misstake as a newline char is treated like any other char and it's stuck in the input buffer. fflush() wont work on input streams but a commonly used "hack" is to put:

    while(getchar() != '\n');
    after the scanf call. You can define it in a macro if you are going to use it a lot.
  7. larswik thread starter macrumors 68000

    Sep 8, 2006

Share This Page