strncpy和strcat不工作,我认为他们会c ++ [英] strncpy and strcat not working the way I think they would c++

查看:172
本文介绍了strncpy和strcat不工作,我认为他们会c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务来自己实现一个字符串对象,并且当试图连接两个这样的字符串时,它现在被卡住了。我想我会走这条路:


  • 分配足够大的空间来容纳

  • 使用strncpy将字符串保存到新空间中(本部分工作原理)

  • 在字符串上的猫我插入

  • 持有字符串



执行:

  #include< iostream> 
#include< cstring>

使用namespace std;

int main(){
int index = 6; //插入位置

char * temp = new char [21];
char * mystr = new char [21 + 7 +1];
char * insert = new char [7];

temp =你好,这是一个测试;
insert =world;

strncpy(mystr,temp,index);
strcat(mystr + 7,insert);
strcat(mystr,temp + index);
mystr [21 + 6] ='\0';

cout<< mystr:<< mystr<< ENDL;

返回0;
}

代码在使用可视化工作室时在Hello之后打印乱码,但在使用g ++(有警告),为什么差异?

解决方案

您将c本机概念与c ++混合使用。不是一个好主意。



这更好:

  #include <&的iostream GT; 
#include< string> //不是cstring

using namespace std;

int main(){
int index = 6; //插入位置

字符串temp =你好,这是一个测试;
string insert =world;
string mystr = temp.substr(0,index)+ insert + temp.substr(index);

cout<< mystr:<< mystr<< ENDL;

返回0;
}


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?

解决方案

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

这篇关于strncpy和strcat不工作,我认为他们会c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆