Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;从文件写入std::string*var_C++_String_File_Pointers_Char - Fatal编程技术网

C++ C++;从文件写入std::string*var

C++ C++;从文件写入std::string*var,c++,string,file,pointers,char,C++,String,File,Pointers,Char,实际上,我在将单个字符保存到字符串*时遇到了一个问题。我有这样一个函数: void保存(std::string*x,const std::string&file) 实际上,我使用循环从文件中提取每个数字,并将其分配给char ch 所以,问题是如何将这个字符附加到字符串*?如果我创建临时字符串并将每个符号添加到此字符串中,然后只执行strcpy或x=temp,我就遇到了分段错误 你能告诉我怎么处理这件事吗 谢谢。听起来像是您正在创建一个本地字符串,然后将其分配给x——类似这样: std::str

实际上,我在将单个字符保存到字符串*时遇到了一个问题。我有这样一个函数:

void保存(std::string*x,const std::string&file)

实际上,我使用循环从文件中提取每个数字,并将其分配给char ch

所以,问题是如何将这个字符附加到字符串*?如果我创建临时字符串并将每个符号添加到此字符串中,然后只执行
strcpy
x=temp
,我就遇到了分段错误

你能告诉我怎么处理这件事吗


谢谢。

听起来像是您正在创建一个本地字符串,然后将其分配给
x
——类似这样:

std::string temp;
// Add to temp
// ...
x = &temp;
std::string save(const std::string &file)
{
  std::string temp;
  // Do stuff...

  return temp;
}
std::string output;
save(output, "path/to/my/file);
问题是,
x
实际上是一个out参数,您将其分配给一个本地参数。当函数超出范围时,本地(
temp
)将被销毁,
x
现在将指向被销毁的内存区域。这将导致访问冲突

最好的方法是更改
保存
,以便它返回字符串。大概是这样的:

std::string temp;
// Add to temp
// ...
x = &temp;
std::string save(const std::string &file)
{
  std::string temp;
  // Do stuff...

  return temp;
}
std::string output;
save(output, "path/to/my/file);
现在,字符串将被正确地复制(如果您是C++11,则将其移动)回调用方。您可以使用
push_back
temp
添加字符

如果不想返回字符串,请传递对用户提供的字符串的引用,并填写:

void save(std::string &x, const std::string &file)
{
  char temp;
  x.push_back(temp);
}
然后这样称呼它:

std::string temp;
// Add to temp
// ...
x = &temp;
std::string save(const std::string &file)
{
  std::string temp;
  // Do stuff...

  return temp;
}
std::string output;
save(output, "path/to/my/file);

永远不要直接更改std::string的缓冲区,因为它有自己的内存管理方法

相反,您应该使用
append()
方法:

char temp;
//...
if(x)  //check for nullptr
{
    x->append(1, temp);  //appends the char 'temp' once
}

向我们展示一些代码,你可以发布一些代码..?std::string s=“test”;s+=“_追加_文本”/*等于*/std::string ps=&s*ps+=“\u更多\u附加的\u文本”//纯std::string处理不需要strcpy,当然这也适用于char:std::string s=“test”;s+='c';/*等于*/std::string ps=&s*ps+='C'<代码>*x+=温度
是修改调用方的
std::string
的正确代码,通过指针作为
x
传入。问题是我无法返回临时字符串。正如您前面提到的,x将指向内存中被破坏的部分,这就是问题所在。有没有办法复制字符串而不返回?@Alex-我已经更新了我的答案,以显示一个使用引用的示例。@Alex这不是真的。字符串的值是字符串的内容。按值返回字符串效果很好。这是安全的:
std::string add1(const char*j){string s=j;s+=“1”;返回s;}
。您正在按值返回字符串的内容。@Alex正如David指出的那样,返回
std::string
很好,因为复制/移动构造函数负责转移内存。