简体   繁体   English

为什么数组不在这里打印出来? (c++)

[英]Why is the array not printing out here? (c++)

The array I have is我的数组是

int age[5] = {11,2,23,4,15}

but it does not print out 11,2,23,4, 15 .但它不会打印出11,2,23,4, 15

#include <iostream>
#include <array>

using namespace std;

int main() {
  int age[5] = {11,2,23,4,15};
  
  cout << age[5] << endl;
}

The name of the array is not age[5] .数组的名称不是age[5]

The name of the array is age .数组的名称是age

The expression age[5] represents the array's sixth element, which does not exist.表达式age[5]表示数组的第六个元素,该元素不存在。

In fact, there is no built-in logic for printing a whole array in a formatted manner, so even cout << age << endl is not correct.事实上,没有以格式化方式打印整个数组的内置逻辑,所以即使cout << age << endl也不正确。

If you want to print the array, do it element-by-element in a loop.如果要打印数组,请在循环中逐个元素地打印。

Arrays are 0-indexed. Arrays 是 0 索引的。 In your example, the valid indexes are 0..4.在您的示例中,有效索引为 0..4。 You are trying to print a single int from age[5] , which is out of bounds.您正在尝试从age[5]打印单个int ,这是越界的。

You need to loop through the indexes of the array, eg:您需要遍历数组的索引,例如:

#include <iostream>
using namespace std;

int main() {
  int age[5] = {11,2,23,4,15};
  
  for(int i = 0; i < 5; ++i) {
      cout << age[i] << " ";
  }
  cout << endl;
}

Alternatively:或者:

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

int main() {
  array<int, 5> age{11,2,23,4,15};
  
  for(int val : age) {
      cout << val << " ";
  }
  cout << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM