strncpy (sl,s2,n)函数从s2复制n个字符给sl,并在必要时截断s2或为其填充额外的空字符。如果s2的长度等于或大于n,目标字符串就没有标志结束的空字符。函数返回sl。自己编写这个函数,并在一个使用循环语句为这个函数提供输入的完整程序中进行测试。
#include <stdio.h> char *mystrncpy(char *p1, char *p2, int n); int main(void) { char str1[81]; char str2[81]; int n; do { puts("input string1:"); gets(str1); puts("input string2:"); gets(str2); puts("input the number of copying char:"); scanf("%d",&n); getchar(); puts("After copying:"); puts(mystrncpy(str1, str2, n)); puts("input any char except q to go on."); gets(str1); } while(*str1 != 'q'); puts("Quit."); return 0; } char *mystrncpy(char *p1, char *p2, int n) { char *p=p1; while(*p1++ != '\0') continue; *--p1 = *p2; n--; while(n>0 && *p2 != '\0') { *++p1 = *++p2; n--; } return p; }
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题