我有一个自己实现一个字符串对象的赋值,当我试图连接两个这样的字符串时,我目前卡住了。我想我会走这条路:
实施:
#include <iostream>
#include <cstring>
using namespace std;
int main(){
int index = 6;//insertion position
char * temp = new char[21];
char * mystr = new char[21 + 7 +1];
char * insert = new char[7];
temp = "Hello this is a test";
insert = " world ";
strncpy(mystr, temp, index);
strcat(mystr + 7, insert);
strcat(mystr, temp + index);
mystr[21 + 6] = '\0';
cout << "mystr: " << mystr << endl;
return 0;
}
该代码在使用可视工作室时打印出Hello后的乱码,但在使用g ++(带警告)时有效,为什么会出现差异?
答案 0 :(得分:1)
您将原生c概念与c ++混合在一起。不是个好主意。
这样更好:
#include <iostream>
#include <string> // not cstring
using namespace std;
int main(){
int index = 6;//insertion position
string temp = "Hello this is a test";
string insert = "world ";
string mystr = temp.substr(0, index) + insert + temp.substr(index);
cout << "mystr: " << mystr << endl;
return 0;
}