编写函数disp(char *s , char *output , int n),实现从s指向的字符串中提取前n个 在9点20之前回答加分

编写函数disp(char *s , char *output , int n),实现从s指向的字符串中提取前n个字符,若字符串中不够n个字符,
则提取到字符串结束符为止,将提取的字符串拷贝(不能用字符串拷贝库函数)到output数组中。再编写一个主函数,
从键盘输入一个字符串src,调用函数disp(),将src字符串中的第4到第10个之间的字符串提取到out数组(在主函数
中定义)中并显示输出。

#include <stdio.h>
#include <string.h>

void disp(char* s, char* output, int n)
{
while (n > 0)
{
if (*s == '\0') break;
*output++ = *s++;
--n;
}

*output = '\0';
}

int main()
{
const int start_pos = 4;
const int end_pos = 10;
int out_length = end_pos - start_pos + 1;
char src[1024];
char out[out_length + 1];

while (1)
{
printf("输入字符串:");
scanf("%s", src);
if (strlen(src) >= start_pos)
break;
else
printf("字符串不够长, 需要至少 %d 个字符\n", start_pos);
}

memset(out, 0, out_length + 1);
disp(src + start_pos - 1, out, out_length);
printf("%s", out);

return 0;
}追问

我是初学者,可以写的简单一点吗?就用C语言

追答

这就是是C语言,没法再简化了。

追问

编译的时候有错误,我看不懂,不会改.....

追答

你要是用 Visual Studio,
char out[out_length + 1]; 改成 char* out = (char*)malloc(out_length + 1);
return前加free(out)

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-06-20
#include <stdio.h>
#include <string.h>

void disp(char *s , char *output , int n)
{
if(strlen(output) <= 10)
{
printf("output长度小于10");
return;
}
int lens = strlen(s);
if(lens < 10)
{
strcpy(output, s);
}
else
{
strncpy(output, s, 10);
}
}

int main()
{
char src[20];
char output[100];
scanf("%s", src);
disp(src+3, output, 7);
printf("%s", output);

getchar();
getchar();
return 0;
}追问

E:\C\src.c(11) : error C2143: syntax error : missing ';' before 'type'
E:\C\src.c(12) : error C2065: 'lens' : undeclared identifier
执行 cl.exe 时出错.

追答

把函数写成这样吧,你试试,反正也不需要判断
void disp(char *s , char *output , int n)
{
int lens = strlen(s);
if(lens < 10)
{
strcpy(output, s);
}
else
{
strncpy(output, s, 10);
}
}

本回答被网友采纳