问题
I have an assignment to implement a string object ourselves, and am currently stuck when trying to concatenate two such strings. I figured I would go this route:
- allocate big enough space to hold
- insert beginning of holding string into new space up to index using strncpy(this part works)
- cat on the string I am inserting
- cat on the remainder of the holding string
Implementation:
#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;
}
that code prints out gibberish after Hello when using visual studios, but works when using g++ (with warnings), why the discrepancy?
回答1:
You're mixing native c concepts with c++. Not a good idea.
This is better:
#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;
}
来源:https://stackoverflow.com/questions/29283567/strncpy-and-strcat-not-working-the-way-i-think-they-would-c