|
-
Aug 28th, 2002, 09:17 PM
#1
Thread Starter
Addicted Member
How do convert string to char?
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
-
Aug 28th, 2002, 10:04 PM
#2
Frenzied Member
Use the [] operator:
Code:
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:
Code:
#include <iostream>
int myFunc(const char* c)
{
std::cout << c << std::endl;
}
int main()
{
string s("Hello");
myFunc(s.c_str());
return 0;
}
Z.
-
Aug 29th, 2002, 06:33 AM
#3
Thread Starter
Addicted Member
Hi Z,
Thanks!
Code:
#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
-
Aug 29th, 2002, 10:48 AM
#4
Frenzied Member
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.
-
Aug 29th, 2002, 02:14 PM
#5
Thread Starter
Addicted Member
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
-
Aug 30th, 2002, 07:31 AM
#6
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;
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Aug 31st, 2002, 09:35 PM
#7
Thread Starter
Addicted Member
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|