qfedu-c-level/day11/homework/h7.c

17 lines
619 B
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 编写一个程序要求用户输入一个字符串然后使用strncpy函数将字符串的一部分复制到另一个字符数组中但限制复制的长度为原字符串的一半并打印复制后的字符串。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char s1[100];
printf("请输入一个字符串: ");
fgets(s1, sizeof(s1), stdin); // scanf() 不能接收换行,故改用 fgets()
char *s2 = (char *)malloc(strlen(s1) / 2 * sizeof(char *));
strncpy(s2, s1, strlen(s1) / 2);
printf("复制后的字符串结果为: %s", s2);
return 0;
}