Conversion from char* to string

Hello,

My code snippet for conversion is as follows:

string temp_file;
temp_file = my_dir;
temp_file += string ("\\file.tmp");

the my_dir is externed from some other file & is char* with a directory path as its value ("C:\\Projects"). If i print temp_file, i get garbage value.So, I'm gettin an exception & the application closes.
i want to know what is the mistake i've been doing.

Thanx in advance
Presumably we're talking about std::string from the standard library <string> header?

You're code is potentially valid. It is dependent on whether my_dir actually points to what you think it does (i.e. have you initialised it?) and whether its null terminated. If you initialised my_dir using the a = "My text!"; syntax then the type of my_dir should be const char*, not just char*.

A variant on your code...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

using namespace std;

const char* a = "Fish";

int main()
{
   string b;
   b = a;
   b += string("Spam");
   cout << b;
}


This is valid and prints "FishSpam" to the standard output stream.
Topic archived. No new replies allowed.