[英]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.