c++ - 使用 C++ 中的函数在第三个中连接两个 char 数组所需的调试帮助
问题描述
我只是不知道为什么它没有编译。花了一个小时后,我决定向你们寻求帮助。根据我的理解,第一个“for”循环肯定会将整个字符串 s1 复制到 s3。我不知道它为什么会崩溃。实际上我很天真地编程更多地被称为“C++初学者”。所以我不想使用内置函数,因为我正在学习用户定义函数的概念。我将 main() 中的函数称为 string_cat(s1,s2);
void string_cat(char *s1, char*s2){
char s3[200]; int i = 0, j = 0;
for (i=0; s1[i] != '\0'; i++){
s3[i] = s1[i];
}
while (s3[i] != '\0')
{
i++;
}
while (s2[j] != '\0')
{
s3[i++] = s2[j++];
}
s3[i] = NULL;
cout << s3 << endl;
}
解决方案
我对您的代码进行了微小的更改:
#include<iostream>
using namespace std;
void string_cat(char *s1, char*s2)
{
char s3[200]; int i = 0, j = 0;
for (i=0; s1[i] != '\0'; i++){
s3[i] = s1[i];
}
while (s2[j] != '\0')
{
s3[i++] = s2[j++];
}
s3[i] = '\0';
cout << s3 << endl;
}
int main()
{
char str1[5] = "abcd";
char str2[5] = "efgh";
string_cat(str1, str2);
}
你应该写: s3[i] = '\0';
编译:
$ g++ StringMerge.cpp -o StringMerge.o
跑:
$ ./StringMerge.o
abcdefgh
推荐阅读
- python - 检查数组的轴是否为零值
- azure - 从 Azure 数据工厂中的 csv 中选择最后一行
- flutter - 如何在flutter中播放来自api请求的视频url,我使用了视频播放器包但不包括返回或退出屏幕?
- vue.js - vue.draggable 不同的拖放区
- three.js - 在 ThreeJS 中拼接网格会导致可见的接缝
- node.js - 通过 Nodejs 上的 npm 请求模块发出 POST 请求时出现 CERT_HAS_EXPIRED 错误,但证书有效
- sql-server - 将 nvarchar(max) 从存储过程传递到 SSIS
- c# - 构建自定义 Blazor 组件时是否可以使组件参数成为必需?
- discord.js - 如何输入/找到正确的令牌或错误?
- spring - 引起:java.lang.IllegalArgumentException:应用程序上下文不能为空