【发布时间】:2019-03-26 05:04:35
【问题描述】:
我是 C 和 C++ 编程的新手,谁能给我提示一下我在这里做错了什么。我正在尝试写入 concat 函数,该函数需要指向字符的指针并将第二个连接到第一个。代码确实这样做了,但问题是它在最后添加了一堆垃圾。例如,当传递参数“green”和“blue”时,输出将是“greenblue”加上一堆随机字符。我还写了 strcat 使用的 strlen 函数,我将在下面提供以供参考。我正在使用https://www.onlinegdb.com/online_c++_compiler 的在线编译器 确切的说明和规范是这样的:
strcat(char *__s1, const char *__s2) 函数将 __s2 的内容以 __s1 的 NULL 字符开头连接到 __s1。注意:连接包括 __s2 的 NULL 字符。该函数返回 __s1。
int main(int argc, char** argv)
{
const int MAX = 100;
char s1[MAX];
char s2[MAX];
cout << "Enter your first string up to 99 characters. ";
cin.getline(s1, sizeof(s1));
int size_s1 = strlen(s1);
cout << "Length of first string is " << size_s1 << "\n";
cout << "Enter your second string up to 99 characters. ";
cin.getline(s2, sizeof(s2));
int size_s2 = strlen(s2);
cout << "Length of second string is " << size_s2 << "\n";
cout << " Now the first string will be concatenated with the second
string ";
char* a = strcat(s1,s2);
for(int i = 0; i<MAX; i++)
cout <<a[i];
// system("pause");
return 0;
}
//strcat function to contatenate two strings
char* strcat(char *__s1, const char *__s2)
{
int indexOfs1 = strlen(__s1);
int s2L = strlen(__s2);
cout <<s2L << "\n";
int indexOfs2 = 0;
do{
__s1[indexOfs1] = __s2[indexOfs2];
indexOfs1++;
indexOfs2++;
}while(indexOfs2 < s2L);
return __s1;
}
//Returns length of char array
size_t strlen(const char *__s)
{
int count = 0;
int i;
for (i = 0; __s[i] != '\0'; i++)
count++;
return (count) / sizeof(__s[0]);
}
【问题讨论】:
-
没看细节,你可能忘记放NUL终结符了。另请注意,包含双下划线 (
__) 的标识符是为实现保留的。 -
如果在
while(indexOfs2 < s2L);中将<更改为<=会有帮助吗? -
不要在变量名或其他标识符的开头使用
__。__通常保留给编译器使用。你也不应该使用_(单下划线)。 -
你应该给你的函数起不同的名字给标准库函数,这是保留的