在c程序中打印一个单词的每个字符

to print each character of a word in c program

我有一个 c 程序,可以逐个字母地打印单词。我从这个 link 引用了这个程序 https://www.tutorialgateway.org/c-program-to-print-characters-in-a-string/。如果我 运行 这个程序在在线 c 编译器中给出了准确的结果,但在 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] != '[=10=]'; i++)
    {
        printf("The Character at %d Index Position = %c \n", i, str[i]);
    }
    return 0;
}

这个程序没有通过任何错误,但我不知道为什么这个程序没有打印结果。

尝试 fgets(str, 100, stdin) 而不是 scanf()。这是将一行读入缓冲区的常规方法。当我使用 scanf() 时,我只得到了部分输出,因为它会在 space.

处停止读取字符串

IDK 你的输出是什么,但这是我的:

 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

这是正常的,因为:

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 ('[=16=]'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.

这取自 scanf

编辑: 只是为了好玩,您可以使用 scanf

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

这会将 \n 换行符替换为 '\0'。

注意:@Joshua 的答案更安全,如果您想知道为什么 google 为什么我不应该使用 scanf()