我正在尝试打印const的值,但它不起作用。我在多年后回到了C++,所以我知道造型是一个可能的解决方案,但我也不能让它工作。
代码如下:
//the number 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;我正在尝试打印‘row’的值,但没有成功。
发布于 2011-06-07 02:10:12
您需要:
cout << endl << "Rows : " << rows;注这与const无关- C++不允许您使用+运算符连接字符串和数字。你真正在做的是一个叫做指针运算的神秘的东西。
发布于 2011-06-07 02:10:18
你就快成功了:
cout << endl << "Rows : " << rows;错误是因为"Rows : "是一个字符串文字,因此是一个常量,并且通常不会像您想象的那样被修改。
更进一步,您可能使用了+ (通俗地用作连接操作),假设您需要构建一个字符串来提供给输出流。相反,operator <<在完成时返回输出流,从而允许链接。
// It is almost as if you did:
(((cout << endl) << "Rows : ") << rows)发布于 2011-06-07 02:11:16
我认为你想要:
std::cout << std::endl << "Rows : " << rows << std::endl;我经常犯这个错误,因为我也经常使用java。
https://stackoverflow.com/questions/6256197
复制相似问题