Thread: why scanf() dont working?

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    14

    why scanf() dont working?

    Code:
    #include <stdio.h>
    #include <conio.h>
    
    void main()
    {
    int n;
    char ch;
    clrscr();
    
    do
    {
    printf("Enter number:  ");
    scanf("%d",&n);
    printf("Square of %d is %d",n,n*n);
    
    printf("Do you want to enter another?");
    scanf("%c",&ch);
    }while(ch=='y')
    
    }
    here the program get terminated immidiately at statement: scanf("%c",&ch);

    plz tell me why this happens.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Quote Originally Posted by RAJJUMOTE View Post
    plz tell me why this happens.
    The first scanf (reading an int ) leaves the terminating '\n' ( you press enter ) in the buffer.
    The second scanf ( reading a char ) returns that '\n'.
    Kurt

  3. #3
    Captain - Lover of the C
    Join Date
    May 2005
    Posts
    341
    1. Indent your code!
    2. Its int main() never void main()
    3. conio.h isn't portable and people frown on its functions. Don't use it.
    4. clrscr() comes from conio.h. See #1
    5. You're missing a ';' semicolon after your do-while-statement.
    6. Put a '\n' newline in your second printf() statement so it looks a little organized.
    7. scanf() is also frowned on. An alternative:
    Code:
    ch = fgetc(stdin);
    8. To your main question: Why does it not work? It's because after you typed your number, you hit enter. The '\n' stays in the stdin buffer. When you get the next character after the number, it is going to be '\n'. You have to clear this out of the buffer by calling fgetc(stdin); sometime between where the user enters the number and when you read the character.
    Don't quote me on that... ...seriously

  4. #4
    Registered User
    Join Date
    Nov 2006
    Location
    Coimbra, Portugal
    Posts
    64
    Quote Originally Posted by ZuK View Post
    The first scanf (reading an int ) leaves the terminating '\n' ( you press enter ) in the buffer.
    The second scanf ( reading a char ) returns that '\n'.
    Kurt
    If I'm not mistaken, some operating systems also leave a '\r' before the '\n'. I think those scanf calls should be converted to fgets + sscanf.
    Name: Miguel Martins
    Date of birth: 14th August 1987

    "He who hesitates is lost."

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    230
    or you can use the following code after the between the scanf calls:
    Code:
    while ((c=getchar()) != '\n')
        ;
    of course you will have to declare the variable "c" before you use it.
    What this does is basically "throw away" everything in the input buffer (stdin) until a '\n' is found (which is also thrown away).

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    > If I'm not mistaken, some operating systems also leave a '\r' before the '\n'.
    Only if you can manage to get the input stream into "binary" mode.
    Irrespective of the OS native line ending mode (assuming they even have one), code using the standard API will only see a \n at the end of each line.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    Dec 2006
    Posts
    14
    Thanks to all friends

  8. #8
    Super unModrator
    Join Date
    Dec 2007
    Posts
    321
    Hey ,this program works->
    Code:
    #include <stdio.h>
    #include <conio.h>
    
    void main()
    {
    int n;
    char ch;
    clrscr();
    
    do
    {
    printf("Enter number:  ");
    scanf("%d",&n);
    printf("Square of %d is %d",n,n*n);
    fflush(stdin);
    printf("Do you want to enter another?");
    scanf("%c",&ch);
    }while(ch=='y');
    
    }
    I am not sure if im telling u the correct answer as to why it happens but i think i read somewhere that scanf() leaves the return in the buffer when you enter key after entering "n"
    fflush(stdin); cleares the buffer...........(stdin means standard input device which is the keyboard)

    Forgive me for any inaccurateness in the answr as i m a bigginer []

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    void main is undefined; read my signature for more information.
    fflush(stdin) is undefined; read FAQ.
    And indent that mess.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    Quote Originally Posted by abk View Post
    Hey ,this program works->
    Code:
    #include <stdio.h>
    #include <conio.h>
     
    void main()
    {
    int n;
    char ch;
    clrscr();
     
    do
    {
    printf("Enter number:  ");
    scanf("%d",&n);
    printf("Square of %d is %d",n,n*n);
    fflush(stdin);
    printf("Do you want to enter another?");
    scanf("%c",&ch);
    }while(ch=='y');
     
    }
    I am not sure if im telling u the correct answer as to why it happens but i think i read somewhere that scanf() leaves the return in the buffer when you enter key after entering "n"
    fflush(stdin); cleares the buffer...........(stdin means standard input device which is the keyboard)

    Forgive me for any inaccurateness in the answr as i m a bigginer []
    Your code has one lot of non standard functions.

    ssharish

  11. #11
    Captain - Lover of the C
    Join Date
    May 2005
    Posts
    341
    I think you'll like this one better:
    Code:
    #include <stdio.h>
    #include <windows.h> // windows.h is used for clearing the screen
    // Removed conio.h
    
    // Function prototypes
    void clear_screen ( void );
    void clear_buffer(FILE* file);
    
    int main() // int main() instead of void main()
    {
    	int n;
    	char ch;
    
    	clear_screen(); // replaced clrscr();
    
    	do
    	{
    		printf("Enter number:  ");
    		scanf("%d",&n);
    		// Added a '\n' for the sake of the user
    		printf("Square of %d is %d\n",n,n*n); 
    
    		// clear the buffer the windows way
    		clear_buffer(stdin);
    
    		printf("Do you want to enter another?");
    		scanf("%c",&ch);  // Didn't replace this because it's
    			            // pretty safe for char's and int's
    			            // just not for strings
    	}while(ch=='y'); // Added a semi-colon
    
    	return 0; // How any happy program should end
    }
    
    /* This function was copied out of the FAQ
     * Credit: Sunlight
     * Only works on windows but similar functions
     * can be written for other OS's */ 
    void clear_screen ( void )
    {
      DWORD n;                         /* Number of characters written */
      DWORD size;                      /* number of visible characters */
      COORD coord = {0};               /* Top left screen position */
      CONSOLE_SCREEN_BUFFER_INFO csbi;
    
      /* Get a handle to the console */
      HANDLE h = GetStdHandle ( STD_OUTPUT_HANDLE );
    
      GetConsoleScreenBufferInfo ( h, &csbi );
    
      /* Find the number of characters to overwrite */
      size = csbi.dwSize.X * csbi.dwSize.Y;
    
      /* Overwrite the screen buffer with whitespace */
      FillConsoleOutputCharacter ( h, TEXT ( ' ' ), size, coord, &n );
      GetConsoleScreenBufferInfo ( h, &csbi );
      FillConsoleOutputAttribute ( h, csbi.wAttributes, size, coord, &n );
    
      /* Reset the cursor to the top left position */
      SetConsoleCursorPosition ( h, coord );
    }
    
    /* This function is based off 
     * of Abda92's suggestion */
    void clear_buffer(FILE* file)
    {
    	int c;
    	while ((c = fgetc(file)) != '\n');
    }
    Don't quote me on that... ...seriously

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf skips lines of code in DOS using Dev-C++ and Windows XP
    By jenovanomusuko in forum C Programming
    Replies: 9
    Last Post: 12-21-2008, 03:10 AM
  2. Help with a basic scanf procedure.
    By killpoppop in forum C Programming
    Replies: 9
    Last Post: 11-03-2008, 04:39 PM
  3. Using scanf in a for loop
    By agentsmith in forum C Programming
    Replies: 2
    Last Post: 12-18-2007, 09:37 AM
  4. Counter Errors for otherwise working program???
    By jereland in forum C Programming
    Replies: 7
    Last Post: 03-22-2004, 08:37 PM
  5. Quzah's printf and scanf tutorial...
    By quzah in forum C Programming
    Replies: 2
    Last Post: 03-20-2002, 03:59 AM