[英]strncpy and strcat not working the way I think they would c++
我有一个任务自己实现一个字符串对象,并且在尝试连接两个这样的字符串时当前卡住了。 我想我会走这条路:
执行:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.