【问题标题】:How to convert a char[] to a std::string如何将 char[] 转换为 std::string
【发布时间】:2015-11-30 11:29:25
【问题描述】:

我正在尝试将 char[] 转换为 std::string。我到处寻找,我找到了相同的答案,那个字符串有一个构造函数做这个确切的事情。 问题是,它对我不起作用。

这是我的代码:

std::string getKey(double xTop,double yTop,double zTop,double xBottom,double yBottom,double zBottom,double zGridPoint)
{
      std::string outfile = correctPath(getCurrentDirectory().toStdString()) + "keys.txt";
      FILE *f;
      f= fopen(outfile.c_str(),"a");
      char buffer[100];
      double s;

      if((zBottom-zTop) ==0)
      {
            sprintf(buffer,"%e %e %e", xTop, yTop, zTop); 
      }else
      {
            s=(zGridPoint - zTop) / (zBottom - zTop);
            sprintf(buffer,"%e %e %e",xTop+ s*(xBottom - xTop), yTop+ s*(yBottom - yTop), zGridPoint);

      }

      std::string ret (buffer);
      fprintf(f,"buffer: %s ; ret: %s\n",buffer,ret);
      fclose(f);
      return ret;
}

fprintf 用于检查我的字符串是否正确,但事实并非如此。 buffer 打印正确,但 ret 给了我一些奇怪的迹象,我在这里既不能阅读也不能重现。

有人发现我的代码有问题吗?

谢谢

【问题讨论】:

  • 尝试 fprintf(f,"buffer: %s ; ret: %s\n",&buffer,ret);
  • %s 不能与std::string 一起使用。试试fprintf(...,ret.c_str());
  • @hanshenrik 不,这不正确。
  • 不要对 C++ 对象使用旧的 C 样式格式化函数,它根本行不通。编译器应该为此大喊大叫。请改用 C++ 流。
  • 抱歉,没用。 & 完全没有改变。我也试过 fprintf(f,"buffer: %s ; ret: %s\n",&buffer,&ret);

标签: c++


【解决方案1】:

ret 不是char*。但是,printf%s 说明符需要 char*(即 C 样式字符串)。

您可以将printfret.c_str() 一起使用(这使得您的字符串变得不必要,因为您将其直接转换回char 数组)或C++ 输出工具:

fprintf(f, "buffer: %s ; ret: %s\n", buffer, ret.c_str());

std::ofstream f(outfile);
f << ret << std::endl;
f.close();

【讨论】:

    【解决方案2】:

    您不能使用 %s 将字符串对象传递给 printf。

    您需要将ret.c_str() 作为参数传递,或者更好的是,使用cout

    在此处阅读更多信息:C++ printf with std::string?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-14
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 2013-08-26
      • 2013-03-20
      • 2016-06-10
      • 2011-08-02
      相关资源
      最近更新 更多