首页 > 解决方案 > 为什么字符串中包含的空格不起作用?

问题描述

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char firstname[15];
    char lastname[15];
    char crush_first[15];
    char crush_last[15];
    int babies;


    printf("What is your first name?\n");
    scanf("%s", firstname );

    printf("What is your last name?\n");
    scanf(" %s", lastname);
    /* see i have added space before the character conversion but on exectution 
    of this file no space is in between the two strings*/


    printf("What is your crush's first name?\n");
    scanf("%s", crush_first );

    printf("What is your crush's last name?\n");
    scanf(" %s", crush_last );

    printf("How many kids will you have?");
    scanf("%d", &babies );

    printf("%s%s will have a lovely marriage with %s%s and they will have %d kids",firstname,lastname,crush_first,crush_last,babies);

}

现在我要做的是在字符串中默认添加空格。“__etc”我希望字符串也存储这些值。虽然我在 %s 之前反复添加了空格,但它无法识别。

标签: c

解决方案


来自scanf 文档

s   matches a sequence of non-whitespace characters (a string) [...]

此外,如果有人输入的字符串比您的接收缓冲区长,您将溢出缓冲区。

如果您想阅读该行直到换行,也许可以使用 fgets:

fgets(lastname, sizeof(lastname), stdin);

推荐阅读