首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

自各儿写的my_strncpy()函数 帮忙看看

2013-04-21 
自己写的my_strncpy()函数 帮忙看看/******************************************日期:2013-4-176. strncp

自己写的my_strncpy()函数 帮忙看看

/******************************************
日期:2013-4-17

6. strncpy(s1,s2,n) 函数从 s2 复制 n 个字符给 s1, 并在必要时截断 s2 或为其填充额外的空字符.
如果 s2 的长度等于或大于 n . 目标字符串就没有标志结束的空字符. 函数返回 s1 .
自己编写这个函数, 并在一个使用循环语句为这个函数提供输入的完整程序中进行测试.
******************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 80
char *my_strncpy(char *s1, char *s2, int n);
int main()
{
    char input[SIZE];
    char *str1 = NULL;
    int n;

    puts("enter a string:");
    while(gets(input) && input[0] != '\0')
    {
        puts("enter number you copy:");
        while(1 == scanf("%d", &n))
            printf("%s", my_strncpy(str1, input, n));
    }
    return 0;
}
char *my_strncpy(char *s1, char *s2, int n)
{
    char *s = s1;
    int i = 0;
    int len = strlen(s2);

    while(*s2!='\0') //如果字符串s2还未到'\0'
    {
        if(i++ < n)
            *s1++ = *s2++;
        else
        {
            *s1 = '\0';
            break;
        }
    }
    while(n - len >= 0)
    {
        *s1++ = *s2++ = '\0';
        len++;
    }

    return s;
}不知道错哪里了?字符串处理真是麻烦。
String
[解决办法]
引用:
C/C++ code
?



123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051

/****************************************** 日期:2013-4-17   6. strncpy(s1,s2,n) 函数从……
写的比较乱啊,定义的那个s干啥用的?这个要做的比较安全需要几个判断条件:
1:s1和s2不能是空指针
2:如果s1的长度len1 < s2的长度len2,并且这两者长度和n的关系,总之需要确定出一个最多能赋值的字符个数。
3:将s1最后一个有效字符的下一位置为'\0'结束符

热点排行