简体   繁体   中英

I'm having trouble in C++ geting input from a user in a function, adding to an array, and printing that array

I'm learning c++ and I'm trying to ask the user to input 4 numbers in a function, and then simply print the array.

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

    int getNums;

    getNums = getFourNums();

    cout << "The array is: " getNums << endl;
}

int getFourNums(){

    int i;

    int myArray[4];
    cout << "Enter 4 nums: ";
    for(i = 0; i < 4; i++){
        cin >> myArray[i];
    }
    return myArray[i];

As of now, it's letting me get the four numbers, but the result that's printing is "The array is: 0." I'm not quite sure why the array is seemingly not populating.

Your fundamental problem is that int getFourNums() can only return a single integer, not an array of them. The next problem is that functions cannot return raw arrays for historical reasons. Your choices are to return a std::array , a struct containing the array, pass the array by reference into the function, or return a std::vector . My preference for this application is a std::vector - it is flexible, and although not quite as efficient as std::array , you should probably default to std::vector unless you have a good reason otherwise. Your getNums code would then look like:

std::vector<int> getFourNums() {
    std::vector<int> result;
    cout << "Enter 4 nums: ";
    for(int i = 0; i < 4; i++){
        int v;
        cin >> v;
        result.push_back(v);
    }
    return result;
}

To print the vector, see this question . My personal preference would be a range-based for loop over the vector; your tastes may vary.

One issue in your code is that a loop like

for(i = 0; i < 4; i++){
    cin >> myArray[i];
}

will end up with i==4 . Hence, return myArray[i] will exceed array bounds and/or access an uninitialised value then and yield undefined behaviour.

The main issue, however, is that in C++ you'll follow a very different approach and use collection types like std::vector instead of plain arrays. See the following code illustrating this. Hope it helps.

#include <vector>
#include <iostream>

std::vector<int> getFourNums(){

    int val;
    std::vector<int> result;
    cout << "Enter 4 nums: ";
    for(int i = 0; i < 4; i++){
        cin >> val;
        result.push_back(val);
    }
    return result;
}

int main(int argc, char** argv){
    std::vector<int> fourNums = getFourNums();
    for (auto i : fourNums) {
        cout << i << endl;
    }
}

int getFourNums() will only let you return one int , not the whole array and return myArray[i]; is out of bounds since i == 4 . You can only use the range [0,3] as indices for your array. Here's a reworked version with comments in the code.

#include <iostream>
#include <vector>

// don't do "using namespace std;" since it includes
// a lot of stuff you don't need.

// Here's a function that will return a vector of int's
// It'll behave much like a C style array
// but can have variable length and you can use
// a lot of standard functions on it.

std::vector<int> getNums(size_t count) {

    // The "array" we'll return with "count" number of
    // default constructed int:s (they will all be 0):

    std::vector<int> myArray(count);

    std::cout << "Enter " << count << " nums: ";

    // A range based for loop that will go through
    // all int:s in "myArray". "num" will be
    // a reference to each int in the vector which
    // means that if you change the value of "num",
    // you'll actually change the value in the vector.

    for(int& num : myArray) {
        // read values into the int currently
        // referenced by num

        std::cin >> num;
    }

    // return the vector by value
    return myArray;
}

// Put main() last so you don't have to forward declare the functions
// it uses

int main() {

    // call getNums with the value 4 to read 4 int:s
    std::vector<int> Nums = getNums(4);

    std::cout << "The array is:";

    // print each int in the vector. There's no need to use
    // a reference to the int:s here since we won't be changing
    // the value in the vector and copying an int is cheap.

    for(int num : Nums) {
        std::cout << " " << num;
    }

    // std::endl is rarely good when you only want to output a newline.
    // It'll flush the buffer with is costly.
    // Make a habit of using "\n" in most cases.

    std::cout << "\n";
}

I see that you want to return entire array but just look at your return type:

int getFourNums()

You're returning an integer right? In this situation the returned integer is always myArray[4] . Be aware that it's an integer value, you're returning something that doesn't belong to you actually!

So what to do? I suggest you to pass your array to function like this:

 void getFourNums(int myArray[]){
    int i;
    cout << "Enter 4 nums: ";
    for(i = 0; i < SIZE; i++){
        cin >> myArray[i];
    }
}

Now you filled your array. How to print your array then? We can't simply give our array name and tell cout to print it like you did (you couldn't actually!). Nothing magical here. We're going to print your array's element one by one:

void printFourNumbers(int array[])
{
    for(int i = 0 ; i < SIZE ; ++i)
    {
        cout << array[i] << endl;
    }
}

Finally whole code looks like this:

#include <iostream>
using namespace std;
const int SIZE = 4;

void getFourNums(int myArray[]);
void printFourNumbers(int array[]);

int main(int argc, char** argv){
    int myArray[SIZE];
    getFourNums(myArray);
    printFourNumbers(myArray);

}

void getFourNums(int myArray[]){
    int i;
    cout << "Enter 4 nums: ";
    for(i = 0; i < SIZE; i++){
        cin >> myArray[i];
    }
}

void printFourNumbers(int array[])
{
    for(int i = 0 ; i < SIZE ; ++i)
    {
        cout << array[i] << endl;
    }
}

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