我需要用C写一个程序,它将字符串添加到字符串等(例如'5'字符串-它需要读取"vbvbvbvb " 5次)。但它不起作用?请帮助!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char s[80];
int len;
int counter = 0;
char* repeat(char* s, int n) {
if (n > 0) {
if (s[len] == n) {
counter++;
}
len--;
repeat(s, (n++));
}
return s;
}
int main(void) {
printf("%s", repeat("vb", 5));
fflush(stdout);
return EXIT_SUCCESS;
}
您正试图写入"vb"
的末尾,这是常量池中的字符串。不要那样做。分配一个长度为strlen(s) * n + 1
的字符串并写入该字符串
你的基本情况可能是错误的。基本情况应该是n == 0
,即当空字符串(除了下面终止的NUL之外没有附加任何内容)合适时。
您的递归步骤(n++)
可能应该是(n - 1)
以倒数到基本情况。如前所述,后增量做了一个无用的赋值,递归得到与n
相同的值。
我不知道counter
和len
应该做什么,但它们对我来说看起来是多余的。len
是未初始化的,所以s[len]
有未定义的行为。
在写入n
副本后,需要在末尾添加一个终止NUL (' '
),以便printf
和类似的函数可以识别结束
您正在使用s作为全局和局部变量,该函数正在本地工作。尽量不要在不必要的地方使用全局变量。同样,这里不需要递归。
#include <stdio.h>
void concatenate_string(char *dest, const char *src, int n) {
char *s;
while(n--) {
s = (char*)src;
while(*(s))
*(dest++)=*(s++);
}
*(dest++) = 0;
}
int main(void) {
char out[80];
concatenate_string(out, "ab", 5);
printf("%s", out);
return 0;
}