简体   繁体   中英

How do i store user input in an array?

Why isn't my function taking any input and outputing anything? I want to be able to recieve user input, store it in my array and then print out the value(s) stored.

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;
}

This is a great exercise to do if you are just starting to get familiar in working with arrays, good on you! This is how I would implement a program that would accept user input into an array, and then print each element in the array (be sure to read the comments!):

#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;
}

I hope this helps! A great way to learn about what this program is actually doing is to copy and paste this into an IDE and then run a debugger on the code and observe what happens line by line.

I myself at first did this when started arrays , then got the hang of it . You did half of the program correct , that's good , the only mistakes u made are storing the input data in the appropriate variables and displaying them in a wrong format To fix this,

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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