Well, you've declared a buffer of 5 chars
char string[5];
and you can't assign the address of a string to a buffer variable.
string = "Hello"; // :( does not compile
only point at it
const char* msg = "Hello"; // literals should always be const
(the char* pointer variable points at the memory where Hello is stored)
What you can do is copy into or print into, as you aready kind of realised. You use sprintf rather than printf
1 2
|
char buffer[256] = ""; // init buffer to zeros
sprintf(buffer, ""%s", str);
|
With strcpy, you're orig code becomes
1 2 3 4 5 6 7
|
int randomint;
randomint=rand()%20+1;
char string[6]; // added an extra elem so long enough for These + null term!
if(randomstringint==1-10){ // <= this doesn't look right
strcpy(string, "This";} // string is prob a name to avoid, due to std::string
else{
strcpy(string, "These";}
|
Note that "These" needs 6 chars of buffer space. The extra one is for the null terminator.
Andy
PS If by this
if(randomstringint==1-10)
you mean the value is between 1 and 10, then you need
if(randomstringint >= 1 && randomstringint <= 10)
PPS Also see ostringstream
http://www.cplusplus.com/reference/iostream/ostringstream/
char buffer[256] = "";
sprintf(buffer, "%s = %d", name, age);
maps to this
1 2 3 4
|
string str;
ostringstream oss;
oss << name << " =" << age;
str = oss.str();
|