to print each character of a word in c program

2.3k Views Asked by At

I am having a c program which print letter by letter of the word. I referred this program from this link https://www.tutorialgateway.org/c-program-to-print-characters-in-a-string/. If I run this program in online c compiler this gives the exact result, but not working in turbo c++

#include <stdio.h>
int main()
{
    char str[100];
        
    printf("\n Please Enter any String  :  ");
    scanf("%s", str);
        
    for(int i = 0; str[i] != '\0'; i++)
    {
        printf("The Character at %d Index Position = %c \n", i, str[i]);
    }
    return 0;
}

This program doesn't through any error, but I don't know why this program doesn't print the result.

2

There are 2 best solutions below

0
Joshua On BEST ANSWER

Try fgets(str, 100, stdin) instead of scanf(). This is the normal way to read a line into a buffer. When I used scanf() I only got part of the output because it will stop reading a string at a space.

6
AudioBubble On

IDK what is your output, but here is mine:

 Please Enter any String  :  Hell got loose
The Character at 0 Index Position = H 
The Character at 1 Index Position = e 
The Character at 2 Index Position = l 
The Character at 3 Index Position = l

This is normal, due to this:

Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null character ('\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.

this is taken from scanf.

EDIT: Just for the fun, you can do this using scanf

scanf("%[^\n]",str);

this will replace \n newline with '\0'.

NOTE: @Joshua's answer is safer, if you want to know why just google why I shouldn't use scanf()