c ++数组打印hex?

时间:2013-12-12 13:37:43

标签: c++ arrays

希望你们能提供帮助。当我尝试向这个数组添加值,即1,2,3,4时,它将打印为十六进制数字?我怎样才能实际打印非十六进制数组?感谢

int main()
{
    int gr1;
    int gr2;
    int gr3;
    int gr4;
    int addup[4]={gr1, gr2, gr3, gr4};
    cout << "Please enter the first grade";
    cin >> gr1;
    cout << "Please enter the second grade";
    cin >> gr2;
    cout << "Please enter the third grade";
    cin >> gr3;
    cout << "Please enter the fourth grade";
    cin >> gr4;

        cout << addup;

}

4 个答案:

答案 0 :(得分:3)

您正在向阵列中添加未初始化的变量。

int main()
{
    int gr1;
    int gr2;
    int gr3;
    int gr4;
    cout << "Please enter the first grade";
    cin >> gr1;
    cout << "Please enter the second grade";
    cin >> gr2;
    cout << "Please enter the third grade";
    cin >> gr3;
    cout << "Please enter the fourth grade";
    cin >> gr4;

    int addup[4]={gr1, gr2, gr3, gr4};

    for ( int i = 0; i < 4; i++ )
        cout << addup[i];

}

答案 1 :(得分:3)

cout << addup打印内存地址,需要一个for循环来打印出值:

for(int i : addup)
    cout << i << endl;

答案 2 :(得分:2)

因为变量gr1,gr2,gr3,gr4未初始化

int gr1;
int gr2;
int gr3;
int gr4;

数组addup具有未定义的值。

int addup[4]={gr1, gr2, gr3, gr4};

您应该首先为变量赋值,然后才定义数组

int gr1;
int gr2;
int gr3;
int gr4;

cout << "Please enter the first grade";
cin >> gr1;
cout << "Please enter the second grade";
cin >> gr2;
cout << "Please enter the third grade";
cin >> gr3;
cout << "Please enter the fourth grade";
cin >> gr4;

int addup[4]={gr1, gr2, gr3, gr4};

至于这句话

cout << addup;

然后它显示数组的第一个元素的地址。要显示阵列本身,请使用以下构造

for ( int x : addup ) cout << x << ' ';
cout << endl;

答案 3 :(得分:1)

您不能只是格式化数组:没有重载的输出运算符。你可以像这样打印:

std::copy(std::begin(addup), std::end(addup),
          std::ostream_iterator<int>(std::cout, " "));

(假设您使用C ++ 11并包含<iterator><algorithm>)。请注意,即使您打印该值,它们也不是您期望的值:数组在此时使用变量值定义的点处初始化。仅仅因为您稍后更改变量并不意味着它会影响数组:值会在定义时复制,而不会被引用。

请注意,您应该验证是否还应验证您是否确实成功读取了该值,例如使用

if (std::cin >> gr1 >> gr2 >> gr3 >> gr4) {
    // do something with the input
}

如果不进行检查,您可以轻松处理随机数据:您应该始终验证输入是否真正成功。