Thread: Sleep function misbehaving!!

  1. #1
    Registered User
    Join Date
    Aug 2017
    Posts
    28

    Sleep function misbehaving!!

    Here is my code:


    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <conio.h>
    
    
    void main()
    {
        int i, len;
        char arr[20];
    
    
        system("CLS");
    
    
        printf("User enter your name: \a");
        scanf("%s", &arr);
    
    
        len = sizeof(arr);
        printf("\n\nYour name: ");
        for (i = 0; i < len; i++)
        {
            printf("%c", arr[i]);
            Sleep(400);
        }
    
    
        getchar();
    }
    
    
    Attached my program run.
    Attached Images Attached Images Sleep function misbehaving!!-error-png 

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,557
    Why do you think Sleep() is misbehaving?

    It looks to me like your loop is using the incorrect size. Wouldn't the length of the string be a better stopping point than the size of the array?


    Jim

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,508
    While we're waiting for a reply:

    Code:
    void main()
    main returns int, not void.

    Code:
    scanf("%s", &arr);
    You don't need the & there, since "arr" (the name of the array by itself) acts as a pointer to its first element.

    Code:
    len = sizeof(arr);
    If you want to find the length of a string, use strlen instead.

  4. #4
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,732
    If you want to slowly print the characters, you need to flush the output after each one, like this:
    Code:
    printf("%c", arr[i]);
    fflush(stdout);
    Sleep(400);
    You have to do this because normally the output is line-buffered, meaning it waits for a whole line before it displays it to the console.
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to use Sleep function?
    By Jake.c in forum C Programming
    Replies: 1
    Last Post: 01-17-2009, 08:36 AM
  2. sleep function
    By osal in forum C++ Programming
    Replies: 5
    Last Post: 05-04-2005, 12:09 PM
  3. Using the sleep function
    By HyperHelix in forum C++ Programming
    Replies: 3
    Last Post: 04-30-2005, 09:18 AM
  4. The sleep function...
    By Finchie_88 in forum C++ Programming
    Replies: 6
    Last Post: 09-07-2004, 03:19 PM
  5. sleep function
    By subflood in forum C Programming
    Replies: 1
    Last Post: 08-29-2004, 03:11 PM

Tags for this Thread