c++ - strncpy 和 strcat 没有按照我认为的方式工作 C++

标签 c++ visual-studio-2012 g++ c-strings

我有一个任务要自己实现一个字符串对象,目前在尝试连接两个这样的字符串时卡住了。我想我会走这条路:

  • 分配足够大的空间容纳
  • 使用 strncpy 将持有字符串的开头插入新空间直到索引(这部分有效)
  • cat 我正在插入的字符串
  • cat 保留字符串的其余部分

实现:

#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;
}

关于c++ - strncpy 和 strcat 没有按照我认为的方式工作 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29283567/

相关文章:

c++ - 错误链接 2019 c++

c# - 将 Fiddler 与 Windows 应用商店单元测试结合使用

c++ - 对 vtable 的 undefined reference

c++ - 未找到 Windows SDK 注册表变量

c++ - 使用特定于 2012 年 11 月 CTP 的 C++11 功能时,有没有办法抑制 Intellisense 错误?

c++ - 部署 Visual Studio 项目

c++ - gcc 附加 char* 和 char 作为原始指针 ("str"+ 'c' )

c++ - 在 C++ 中对 vector 的 vector 进行排序

c++ - MFC 中的全屏窗口

c++ - 是否存在使用 Purify 导致 SIGABRT 在 g++ 中抛出异常的已知问题?