Click to See Complete Forum and Search --> : How do convert string to char?
ChuckB
Aug 28th, 2002, 09:17 PM
Hi,
I have a function that requires a char. I like working with STL strings because they seem a bit friendlier to me. I would like to do something like this.
string s;
s="Hello";
// ...convert string s to char myChar here..
myChar[]= ????
myFunction(int a, int b, int c, char myChar);
I hope I have explained this well enough.
Regards,
ChuckB
Zaei
Aug 28th, 2002, 10:04 PM
Use the [] operator:
string s("Hello");
char c = s[0];
// c now equals 'H'
If you mean char* (C style string), you can convert from std::string with the .c_str() member of std::string:
#include <iostream>
int myFunc(const char* c)
{
std::cout << c << std::endl;
}
int main()
{
string s("Hello");
myFunc(s.c_str());
return 0;
}
Z.
ChuckB
Aug 29th, 2002, 06:33 AM
Hi Z,
Thanks!
#include <string>
#include <stdlib.h>
#include <iostream>
int myFunc(const char* c)
{
std::cout << c << std::endl;
}
int main(int argc, char *argv[])
{
string s("Hello");
myFunc(s.c_str());
system ("pause");
return 0;
}
I modified it for Dev-C++...thanks again.
Is there a downloadable STL reference file (PDF/HTML) that shows functions with examples? A nice PC reference would be ideal.
Regards,
ChuckB
Zaei
Aug 29th, 2002, 10:48 AM
http://msdn.microsoft.com/library . The Online MSDN should have all the info you need. Since the STL is standard, any documentation you find there should work correctly on any compiler.
Z.
ChuckB
Aug 29th, 2002, 02:14 PM
Z,
I have VC++...duh! When digging through help .chm files on my PC. Anyway, the file named VCLANG.CHM deals with STL and C++ conventions (non-Microsoft stuff). I had the reference the whole time.
Regards,
ChuckB
CornedBee
Aug 30th, 2002, 07:31 AM
And in case you ever need a non-const char*:
string str = "sdfksjdfksjdfkj";
char *sz = new char[str.size()+1];
strcpy(sz, str.c_str());
// ...
delete[] sz;
ChuckB
Aug 31st, 2002, 09:35 PM
Thanks!
You guys have helped in a significant way. I have been building my first C++ OpenGL/GLUT game program. I needed to put camera coordinates on 2D HUD for reference...the above code helped perfectly.
Regards,
ChuckB
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.