如何在C ++中显示数字变量?

时间:2014-10-28 20:59:15

标签: c++ variables cout

我有4个变量叫:number,x,y,z。

x = 1,
y = 2,
z = 3

我希望变量号能够取x,y和z的值,并且能够显示值123

到目前为止我已尝试过这个:

number = x + y + z; but the answer is 6.

number = x << y << z; but the output is not what I want.

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:5)

在C ++中:

cout << x << y << z

在C:

printf("%d%d%d", x, y, z);

或者将它们放在一个字符串中:

ostringstream convert;   // stream used for the conversion

convert << x << y << z; 

std::string result = convert.str(); 

答案 1 :(得分:1)

您可以使用std::to_stringint转换为string,然后+运算符充当连接操作。

#include <string>

std::string concatenated = std::to_string(x) + std::to_string(y) + std::to_string(z);
std::cout << concatenated;

答案 2 :(得分:0)

听起来您可能希望将字符转换为字符串,执行字符串添加,然后转换回数字。

此链接应该有所帮助: [http://www.cplusplus.com/forum/articles/9645/]

答案 3 :(得分:0)

您有很多方法可以获得结果:

  • 数字地:number = x * 100 + y * 10 + z
  • 字符串连接,如Cyber​​
  • 所示
  • 直接使用字符:

    char resul[4];
    resul[0] = '0' + x;
    resul[1] = '0' + y;
    resul[2] = '0' + z;
    resul[3] = '\0';
    

可能还有很多其他人......