简体   繁体   English

C++ - 用另一个替换数组的 int 元素

[英]C++ - Replace int elements of an array with another

I've been going through the Fourth Edition of C++ Primer, and I'm on a pointer exercise right now.我一直在学习 C++ Primer 的第四版,现在我正在进行指针练习。 The exercise asks to make a program to go through an array and replace the elements with 0. I have this so far:练习要求制作一个程序来遍历数组并将元素替换为 0。到目前为止我有这个:

#include <iostream>

using namespace std;

using std::cout;
using std::endl;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    for (int i = 0; i != 5; i++)
        arr[i] = 0;
        cout << arr[i] << endl;
}

But I'm getting an error:但我收到一个错误:

name lookup of 'i' changed for ISO 'for' scoping

How do I change the element?我如何更改元素?

your loop should go like this:你的循环应该是这样的:

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

I also recommend you put return 0;我还建议你把return 0; before the final } .在决赛之前}

for (int i = 0; i != 5; i++)
    arr[i] = 0;
    cout << arr[i] << endl;

You forgot { and } .你忘记了{} This means that the line starting cout is not presently part of the loop and, thus, i is out of scope.这意味着开始cout的行目前不是循环的一部分,因此i超出了范围。

The error is a little misleading because it's focusing on the point that this used to be valid, many many many years ago.该错误有点误导,因为它着重于很多年前这曾经有效的观点。

But unlike some other languages, block scope is defined by { and } and not by indentation.但与其他一些语言不同,块作用域是由{}定义的,而不是由缩进定义的。 Thus, write:因此,写:

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

for great success.取得巨大成功。

Well, it should be like this instead: Remember the 5 elements only go from array indices 0 to 4 !好吧,它应该是这样的:记住这 5 个元素只从数组索引0 to 4

#include <iostream>

using namespace std;

using std::cout;
using std::endl;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    for (int i = 0; i < 5; i++){
        arr[i] = 0;
        cout << arr[i] << endl;
    }
}

Change the != to < and add the Curly brackets for the for loop.!=更改为<并为for循环添加大括号。

Your for loop is missing it's body.您的 for 循环缺少它的主体。 You need curly braces around你需要花括号

arr[i] = 0;
cout << arr[i] << endl;

so the compiler knows that code is the body of the for loop.所以编译器知道代码是 for 循环的主体。

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

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