基于循环的范围错误地输出具有cout

时间:2015-05-29 21:26:18

标签: c++ arrays

以下代码正确地输出前两个for语句的数组元素,但是在第三个中,它在使用cout时使用基于for循环的范围错误地输出数组的元素(在第一个中使用printf)。这是为什么?

#include <iostream>
using namespace std;

int main( int argc, char ** argv )
{

int myArray[]={10,20,30,40,50};

for (int i : myArray) {
    printf("%d\n", i);
}


for (int i = 0 ; i < 5; i++) {
    cout << myArray[i] << endl;
}

for (int i : myArray) {
    cout << myArray[i] << endl;
}


return 0;
}

输出:

10
20
30
40
50
10
20
30
40
50
-1707465271
0
1606417258
1606417820
1606418039

3 个答案:

答案 0 :(得分:4)

您在

中有超出限制的访问权限
for (int i : myArray) {
    cout << myArray[i] << endl;
}

i为10,20,30,40,50。

你想要

for (int i : myArray) {
    cout << i << endl;
}

printf一样。

答案 1 :(得分:1)

按以下方式更改

for (int i : myArray) {
    cout << i << endl;
}

与使用printf

之前编写的循环相同
for (int i : myArray) {
    printf("%d\n", i);
}

考虑到您应该包含标题<cstdio>

答案 2 :(得分:0)

在使用基于范围的for循环时,您不需要使用索引变量,而是需要一个局部变量来从需要循环的容器或数组中检索数据

for (int i : myArray) {
    cout << myArray[i] << endl;
}

上面的代码片段应该如下更正:

for (int i : myArray) {
    cout << i << endl;
}
相关问题