c++ - 需要有关使用 for 循环显示我的数组的帮助

标签 c++ loops c++11 for-loop

我知道 C++11 执行此操作的方式,但我被告知要使用“传统”方式。

无论如何,这是代码:

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

int main()
{
  int items[ 5 ] = {1, 2, 3, 4, 5};

  cout << "items before modification: ";
  for( unsigned int whatever = 0; whatever < sizeof(items); whatever++ )
  {
    cout << items[ whatever ] << " ";
  }
}

这是输出:

items before modification: 1 2 3 4 5 1 -1073949596 -1073949588 -1073949744 -1217175552 0 0 -1218570461 134514560 0 0 -1218570461 1 -1073949596 -1073949588

我哪里出错了,因为我期待这个输出:

items before modification: 1 2 3 4 5

最佳答案

sizeof(items) = 项目数量 * 每个项目的大小。您可能想要不。仅包含项目,因此也将其除以每个项目的大小

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

int main()
{
 int items[ 5 ] = {1, 2, 3, 4, 5};

 cout << "items before modification: ";
 for( unsigned int whatever = 0; whatever < sizeof(items)/sizeof(int);    whatever++ )
 {
  cout << items[ whatever ] << " ";
 }
}

关于c++ - 需要有关使用 for 循环显示我的数组的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29921399/

相关文章:

c++ - 这第二个是什么新东西?

c++ - 在 x 次循环后退出 while 循环

c++ - Gtk::Main 和 Gtk::Application::create 之间有什么区别?

c++ - lldb: vector 元素的自定义摘要(C++)

c - 在行号出现中生成第一个索引 '' 3 的函数''

c++ - 固定宽度整数类型的整数文字

c++ - 模板并不总是猜测初始化列表类型

c++ - 通用模板函数总是返回整数值

c++ - 不能使用 cv::fileStorgae 来保存 XML 文件

python - 在循环行中调用函数并将返回值存储到变量中,然后在循环中使用?