Thread: scanf problem

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    9

    scanf problem

    Code:
    #include <stdio.h>
      int main()
      {
          char c;
          scanf("%c",&c);
          printf("%c\n",c);
    
          scanf(" %c",&c);  //there is a space (" %c"
          printf("%c\n",c);
    
          return 0;
      }
    this is the o/p;
    a
    a
    b
    b
    case 2:
    Code:
    #include <stdio.h>
      int main()
      {
          char c;
          scanf("%c",&c);
          printf("%c\n",c);
    
          scanf("%c",&c);     /////there is no space
          printf("%c\n",c);
    
          return 0;
      }
    o/p:
    a
    a


    program terminates...doesn't ask for second input ?
    help me ....

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    In version 2 the second scanf returns the '\n' left in the buffer after the first scanf.
    in version 1 " %c" (with space ) tells scanf to skip leading whitespace ( '\n' is whitespace )
    Kurt

  3. #3
    Registered User
    Join Date
    Jan 2006
    Location
    Berkeley, Ca
    Posts
    195
    change

    Code:
    scanf("%c",&c);
    
    and 
    
    scanf("%c",&c);
    
    to
    
    scanf("%s",&c);
    
    scanf("%s",&c);
    Last edited by cdalten; 01-30-2006 at 08:45 AM.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No, that's wrong. For two reasons:
    1 - You don't have an array, so you can't read strings (ie: %s is for strings).
    2 - Even if you did have an array, you don't use & with array names to read into a string.

    If you did have an array, you might do something like this:
    Code:
    char buf[ BUFSIZ ] = {0};
    ...
    scanf( "%s", buf );
    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with RPC and scanf
    By Ricardo_R5 in forum C Programming
    Replies: 11
    Last Post: 01-08-2007, 06:15 PM
  2. Problem with scanf float..
    By aydin1 in forum C Programming
    Replies: 6
    Last Post: 03-06-2005, 01:35 PM
  3. scanf problem
    By gsoft in forum C Programming
    Replies: 3
    Last Post: 01-05-2005, 12:42 AM
  4. problem with looping scanf
    By crag2804 in forum C Programming
    Replies: 6
    Last Post: 09-12-2002, 08:10 PM
  5. scanf problem
    By Flikm in forum C Programming
    Replies: 2
    Last Post: 11-05-2001, 01:48 PM