簡體   English   中英

strncpy和strcat無法按照我認為的方式工作c ++

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

我有一個任務自己實現一個字符串對象,並且在嘗試連接兩個這樣的字符串時當前卡住了。 我想我會走這條路:

  • 分配足夠的空間來容納
  • 使用strncpy將保持字符串的開頭插入新空間直至索引(此部分有效)
  • 我要插入的字符串上的貓
  • 持有弦的其余部分上的貓

執行:

#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM