c++ - 给出意外输出的基本 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。为什么我在上述两个代码示例中收到不同的输出?
解决方案
阅读您的代码并回答我,与数组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;
}
推荐阅读
- python - 为什么不启用 sqlite3 回调回溯
- database - 计算一组属性的闭包时如何处理组合实体类型
- mysql - 将子查询更改为 windows 功能
- c - 映射到 C 数据类型的 C 自定义数据类型分组在单个结构下
- python-3.x - 为什么“str(print(“hello”)+“one”)”在python中打印“hello noneone”?
- azure - 覆盖 Azure 中的现有 SSL 绑定
- jquery - 无法使用js重定向到新页面
- python - __init__() 不当行为?
- .net - AWS EC2 中的服务分段错误
- graph - 如何在 ArangoDB AQL 中进行图联合和交集