having from std string type object, a pointer to non-constant char

How to convert/have from std string type, a pointer to non-constant char

How is this to work
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#using namespace std;
int main(){

string str="foo";

//...
// the 1st arg. require a char*

if (fgets(str, 19, stdin)) 
{
   char c_str[5];
   c_str=str;
   //...
}

//..

}

Thanks
Last edited on
Even if str were another C-style string, you can't just assign values to C-style strings, or raw arrays, like you're trying to do on line 11.

If you absolutely have to use C-style strings for this, then use the std::string::c_str() method to get a pointer to the data held in str, and then use the C strcpy() function to copy it into your c_str array.

But, really, you should avoid using C-style strings, and just use std::string as much as possible.
Last edited on
string str;
char tmp[25];
if (fgets(tmp, 19, stdin)) //inject standard C approach, allocate a char* big enough (tmp) and use it as if in C for a moment.
{
str = tmp; //let c++ copy the char* back to the string.
strcpy(c_str, str.c_str()); //one way, but tmp already has this info, can you avoid an unnecessary copy?

//...
}


Last edited on
Topic archived. No new replies allowed.