0

I would like to convert a C++ string that the user inputs to a c string. The problem is I have no idea how long the c++ string will be and i know the c string has to have one extra space for \n. Is there a way to apply the lenght of the inputed string into the cstring?

egg

string userInput;
char userInputC[?????];

2
Contributors
1
Reply
6
Views
7 Years
Discussion Span
Last Post by jonsca
0

i know the c string has to have one extra space for \n

It needs an extra spot for '\0' the null terminus, not a newline.

If you're trying to use a std::string in a C-string context, just use the .c_str() method of it.
Assume myfunc takes a const char * as an argument

std::string strg = "test";
myfunc(strg.c_str());

If you need to do it by hand, use the .length() method of string

char * st = new char[strg.length()+1];
strcpy(st,strg.c_str());
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.