【问题标题】:How do i store user input in an array?如何将用户输入存储在数组中?
【发布时间】:2019-11-30 15:15:49
【问题描述】:

为什么我的函数不接受任何输入并输出任何东西?我希望能够接收用户输入,将其存储在我的数组中,然后打印出存储的值。

using namespace std;

void Memory(){
    int temp;
    int Mange[3] = {0, 0, 0};

    for(int i = 0; i < sizeof(Mange); i++){
    cin >> temp;
    temp = Mange[i];
    cout << Mange[i];
    }
}

int main() {

    Memory();

    return 0;
}

【问题讨论】:

标签: c++ arrays user-input


【解决方案1】:

如果您刚刚开始熟悉使用数组,这是一个很好的练习,对您有好处!这就是我将如何实现一个程序,该程序将接受用户输入到一个数组中,然后打印数组中的每个元素(一定要阅读 cmets!):

#include <iostream>

using namespace std;

const int MAXSIZE = 3;

void Memory(){
    //initialize array to MAXSIZE (3).
    int Mange[MAXSIZE]; 

    //iterate through array for MAXSIZE amount of times. Each iteration accepts user input.
    for(int i = 0; i < MAXSIZE; i++){
    std::cin >> Mange[i];
    }

    //iterate through array for MAXSIZE amount of times. Each iteration prints each element in the array to console.
    for(int j = 0; j < MAXSIZE; j++){
    std::cout << Mange[j] << std::endl;
    }
}

int main() {
    Memory();
    return 0;
}

我希望这会有所帮助!了解该程序实际在做什么的一个好方法是将其复制并粘贴到 IDE 中,然后在代码上运行调试器并逐行观察发生的情况。

【讨论】:

    【解决方案2】:

    我自己一开始是在启动数组时这样做的,然后就掌握了窍门。你做了一半的程序正确,这很好,你犯的唯一错误是将输入数据存储在适当的变量中并以错误的格式显示它们 为了解决这个问题,

    #include<iostream>
    
    using namespace std;
    
    const int size=3;
    
    void Memory()
    {
        // You don't need variable temp here
        int Mange[size] = {0, 0, 0};
    
        //It's not necessary to keep it zero but it's a good practice to intialize them when declared
    
        for(int i = 0; i < size; i++)
    
        //You can store maximum value of array in diff variable suppose const then use it in condition
    
        {
        cin >> Mange[i];
        cout << Mange[i];
       //You can print it later with a different loop
       }
    
    }
    
    int main() {
        Memory();
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 2016-10-22
      • 1970-01-01
      • 2015-04-27
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多