C++ const casting
I am trying to print the value of a const but it is not working. I am making a return to C++ after years so I know casting is a possible solution but I can't get that working either.
The code is as follows:
//the n开发者_开发技巧umber of blanks surrounding the greeting
const int pad = 0;
//the number of rows and columns to write
const int rows = pad * 2 + 3;
const string::size_type cols = greeting.size() + pad * 2 + 2;
cout << endl << "Rows : " + rows;
I am trying to print the value of 'rows' without success.
You want:
cout << endl << "Rows : " << rows;
Note this has nothing to do with const
- C++ does not allow you to concatenate strings and numbers with the +
operator. What you were actually doing was that mysterious thing called pointer arithmetic.
You're almost there:
cout << endl << "Rows : " << rows;
The error is because "Rows : "
is a string literal, thus is a constant, and generally speaking is not modified as you may think.
Going slightly further, you likely used +
(colloquially used as a concatenation operation) assuming you needed to build a string to give to the output stream. Instead operator <<
returns the output stream when it is done, allowing chaining.
// It is almost as if you did:
(((cout << endl) << "Rows : ") << rows)
I think you want:
std::cout << std::endl << "Rows : " << rows << std::endl;
I make this mistake all the time as I also work with java a lot.
As others have pointed out, you need
std::cout << std::endl << "Rows : " << rows << std::endl;
The reason (or one of the reasons) is that "Rows : "
is a char*
and the +
operator for char*
s doesn't concatenate strings, like the one for std::string
and strings in languages like Java and Python.
精彩评论