首页 > 解决方案 > 给出意外输出的基本 int 数组

问题描述

#include <iostream>
#include <string>
using namespace std;

int num[3]{ 3, 5, 6, };
cout << num[3] << endl;

string y;
getline(cin, y);
return 0;
}

给出 -858993460 的输出

#include <iostream>
#include <string>
using namespace std;

int num[]{ 3, 5, 6, };
cout << num << endl;

string y;
getline(cin, y);
return 0;
}

输出 004FFC48

但我想让我的输出为 356。为什么我在上述两个代码示例中收到不同的输出?

标签: c++arrays

解决方案


阅读您的代码并回答我,与数组y有什么关系吗? 当然不是,只是另一个变量。num

int num[]{ 3, 5, 6, };
_________________________________^__
删除的另一个错误,你只是说你的数组将有 4 个元素并且你没有说最后一个空间中的数字,所以编译器只是把垃圾放在那里然后你打印num变量空间,因为数组就像指针但不一样。
(建议,去掉逗号,记住计算机从第1行到第N行按升序排列)

如果您想要输出 356,您需要将int数据类型转换为char因为string是一组字符。所以制作你自己的字符串化函数

#include <iostream>
#include <string> // is ambiguous because iostream already have string
using namespace std;
// where is the main function?
int num[]{ 3, 5, 6, };
cout << num << endl;// this should be in a for statement at the end of the program because you output the proccesed values

string y; // container of chars
getline(cin, y); //why do you need this?
return 0;
}

固定的:

#include <iostream>
using namespace std;

int main() {
    //just for printing the numbers
    int num[]{3, 5, 6};

    for (int i = 0; i < 3; i++)
        cout << num[i] << endl;

    return 0;
}

推荐阅读