我有一个任务要自己实现一个字符串对象,目前在尝试连接两个这样的字符串时卡住了。我想我会走这条路:
- 分配足够大的空间容纳
- 使用 strncpy 将持有字符串的开头插入新空间直到索引(这部分有效)
- cat 我正在插入的字符串
- cat 保留字符串的其余部分
实现:
#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;
}
该代码在使用 visual studio 时在 Hello 后打印出乱码,但在使用 g++ 时有效(带有警告),为什么会出现差异?
最佳答案
您将原生 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;
}
关于c++ - strncpy 和 strcat 没有按照我认为的方式工作 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29283567/