shish
shish

Reputation: 1

c, can't print characters from a string

i'm trying to create a delay print function (print a character of a string every second).

my code is:

#include <stdio.h>
#include <string.h>
#include <windows.h>

void delayPrint(char* s);

int main(int argc, char * argv[])
{
    delayPrint("ciao");
    return 0;
}

void delayPrint(char* s)
{
    for (int i=0; i<strlen(s); i++)
    {
        Sleep(1);
        printf("%s", s[i]);
    }
}

I can't print a specific character of a string: i can print the entire string in the displayPrint function. Now the function simply does nothing.

I can't understand the problem (Windows 11, mingw) Anyone can help?

Upvotes: -1

Views: 379

Answers (4)

A.A Taofeek
A.A Taofeek

Reputation: 1

It seems you made an error in your placeholder. You should change your %s to %c to print char.

Upvotes: 0

Martin Drl&#237;k
Martin Drl&#237;k

Reputation: 43

Note that your code has Sleep(1). This function takes milliseconds. So it is probably faster than you wanted. For one second you should change it to Sleep(1000).

https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep

Upvotes: 2

amanshri93
amanshri93

Reputation: 73

Shouldn't you be using %c to print the character??

printf("%c", s[i]);

instead of:

 printf("%s", s[i]);

Upvotes: 3

You are providing %s as an argument to printf but your are giving it a character s[i]. printf expects %s to be a pointer to a null-terminated string (which means there should be a \0 character at the end of the string to detect that it ended).

for (int i=0; i<strlen(s); i++)
    {
        Sleep(1);
        printf("%s", s[i]);
    }

You should change %s to %c.

Upvotes: 1

Related Questions