@lwells
Out of interest, do you (already) code in other languages??
Anyway, the problem is general C++, rather than Windows specific...
1 2
|
char boatNum = '4';
cout << ("come in no. " + boatNum + " - you time is up").c_str() << endl;
|
does not make sense in C++.
The brackets force
"come in no. " + boatNum + " - you time is up"
to be evaluated first.
1. Unfortunately, "hello " + 'A' is valid C++.
cout << "hello " + 'A' << endl;
But what is is doing is:
- using the memory address where the string "hello" starts
- casting the char 'A' to an int, with the value 65 (the ascii code of 'A')
- adding this value to the start address, which moves the pointer several chars past the end of this string (this is C++ pointer arithmatic).
That is, the result is a char* pointer value which, if you're "lucky", will point at a different, later bit of you string (if it's long enough). Otherwise it might point at random chars (causing rubbish to printed out in this case) or, if you're unlucky, at invalid memory, which will cause the program to crash.
2. C++ cannot add two C strings (char* values), or any other two pointers
cout << "hello" + " world" << endl;
Visual C++ compiler error:
error C2110: '+' : cannot add two pointers |
3. And of course, you can't call c_str() on anything apart from a C++ object, anyway.
Now...
You can get your code to use the std::string overloads of operator= if you make the following tweak:
cout << (string("come in no. ") + boatNum + " - you time is up") << endl;
Using the first C string to construct a temporary C++ string object means that all subsequent operations are on a C++ string object, not a C char* pointer. The result or string("come in no. ") + boatNum + " - you time is up" is a string, so you can then call its c_str() method.
But I would prob code this as:
1 2 3 4
|
string msg("come in no. ";
msg += boatNum;
msg += " your time is up";
cout << msg << endl;
|
esp. when there a lot of bits, or it's used in a loop, as operator+= is cheaper than operator+ (ever + constructs a temporary instance of your string).
Andy