Myrkjartan
Myrkjartan

Reputation: 186

How to convert a char[] to a std::string

I´m trying to convert a char[] into a std::string. Everywhere I looked, I found the same answer, that string has a constructor doing this exact thing. The trouble is, it doesn´t work for me.

Here is my code:

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

The fprintf is to check if my string is correct, which isn´t the case. buffer gets printed correctly, but ret gives me some strange signs I can neither read nor reproduce here.

Does anyone see a problem with my code?

Thanks

Upvotes: 0

Views: 850

Answers (2)

hlt
hlt

Reputation: 6317

ret isn't a char*. However, printf's %s specifier requires a char* (i.e., a C-style string).

You can either use printf with ret.c_str() (which makes your string unnecessary, because you convert it right back to a char array) or C++ output facilities:

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

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

Upvotes: 2

Naomi
Naomi

Reputation: 5486

You cannot pass a string object into printf using %s.

You need to pass ret.c_str() as a parameter, or better yet, use cout.

Read more here: C++ printf with std::string?

Upvotes: 1

Related Questions