strncpy and strcat not working the way I think they would c++

扶醉桌前 提交于 2019-12-24 22:38:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!