Reputation: 68857
I'm new to C++. I want to make a char*
, but I don't know how.
In Java is it just this:
int player = 0;
int cpu = 0;
String s = "You: " + player + " CPU: " + cpu;
How can I do this? I need a char*
.
I'm focusing on pasting the integer after the string.
Upvotes: 15
Views: 83210
Reputation: 1303
If you're working with C++, just use std::string
. If you're working with char*
, you probably want to work with C directly. In case of C, you can use the sprintf
function:
char* s = // initialized properly
sprintf( s, "You: %d CPU: %d", player, cpu );
Upvotes: 10
Reputation: 44804
It probably would have been for the best if C++ had overloaded the "+" operator like you show. Sadly, they didn't (you can though, if you want to).
There are basicly three methods for converting integer variables to strings in C++; two inherited from C and one new one for C++.
Upvotes: 0
Reputation:
You almost certainly don't want to deal with char * if you can help it - you need the C++ std::string class:
#include <string>
..
string name = "fred";
or the related stringstream class:
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main() {
int player = 0;
int cpu = 0;
ostringstream os;
os << "You: " << player << " CPU: " << cpu;
string s = os.str();
cout << s << endl;
}
if you really need a character pointer (and you haven't said why you think you do), you can get one from a string by using its c_str() member function.
All this should be covered by any introductory C++ text book. If you haven't already bought one, get Accelerated C++. You cannot learn C++ from internet resources alone.
Upvotes: 44
Reputation: 41232
Just call s.c_str( );
.Here you you can see more.
PS. You can use strcpy
to copy the content to new variable and then you will be able to change it.
Upvotes: 2
Reputation: 43477
Consider using stringstreams:
#include <iostream>
#include <sstream>
using namespace std;
int main ()
{
int i = 10;
stringstream t;
t << "test " << i;
cout << t.str();
}
Upvotes: 0
Reputation: 3666
char *
means "pointer to a character".
You can create a pointer to a 'string' like this:
char* myString = "My long string";
Alternatively you can use std::string:
std::string myStdString("Another long string");
const char* myStdString.c_str();
Notice the const at the beginning of the last example. This means you can't change the chars that are pointed to. You can do the same with the first example:
const char* = "My long string";
Upvotes: 1