如何使用 scanf() 保存包含多个单词的字符串

pun*_*her 2 c string char

我刚刚开始用 C 语言编程,我想知道为什么我不能使用 scanf() 存储包含多个单词的字符串。

例如,我输入:“That's an example”,它仅存储第一个单词“That's”

我的代码:

int main(void) {

    char string[100];
    
    printf("Please enter something: ");
    scanf("%s", &string);
    printf("You entered: %s", string);


    return (0);
}
Run Code Online (Sandbox Code Playgroud)

chq*_*lie 5

您可以使用scanf()字符类转换说明符读取多个单词:%[^\n]将在换行符处停止并将其保留在输入流中。请注意,您必须告知要scanf存储到目标数组中的最大字符数,以避免长输入行上出现未定义的行为。将数组传递给 时scanf(),不应将其地址作为 传递&string,而应将string数组作为函数参数传递时衰减为指向其第一个元素的指针。

这是修改后的版本:

#include <stdio.h>

int main(void) {
    char string[100];
    int c;
    
    for (;;) {
        printf("Please enter something: ");
        /* initialize `string` in case the `scanf()` conversion fails on an empty line */
        *string = '\0';
        if (scanf("%99[^\n]", string) == EOF)
            break;
        printf("You entered: %s\n", string);
        /* read the next byte (should be the newline) */
        c = getchar();
        if (c == EOF)   /* end of file */
            break;
        if (c != '\n')
            ungetc(c, stdin);  /* not a newline: push it back */
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

fgets()但请注意,使用此任务要简单得多:

#include <stdio.h>

int main(void) {
    char string[100];
    
    for (;;) {
        printf("Please enter something: ");
        if (!fgets(string, sizeof string, stdin))
            break;
        /* strip the trailing newline, if any */
        string[strcspn(string, "\n")] = '\0';
        printf("You entered: %s\n", string);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)