Search code examples
c++vectormodularity

Trying to call a vector or array into another function


I have been learning vectors and arrays, but guessing I am missing something. For assignment I need program to be modulated and called to main, but I am struggling to find an answer on how to carry vector/array data into other functions to be used.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int getData() {
    int size = 16;
    vector<int> weeklyScore(16, 0);  // initialize
    for (int counter = 0; counter < 16; counter++) {
        cout << "Enter quiz score (0-15) for week " << counter + 1 << " : "
             << endl;
        cin >> weeklyScore.at(counter);  // fill with data
        if (weeklyScore.at(counter) < 0 || weeklyScore.at(counter) > 15) {
            cout << "Please enter a valid score (0-15): " << endl;
            counter--;
        }
    }
    for (int i = 0; i < size; i++) {
        cout << weeklyScore.at(i) << endl;
    }
    return weeklyScore;  // error here
}

int highScore() {  // new function
    int high;
    int i;
    for (i = 0; i < 16; i++) high = 0;
    if (weeklyScore.at(i) > high) {  // use of vector
        high = i;
    }
    cout << "The highest score is: " << high << endl;
    return 0;
}

At this point I am getting error from line 28:

return weeklyScore;
no viable conversion from returned value of type 'vector<int>' to function return type 'int'

Solution

  • First, fix the return type to match the value being returned.

    vector<int> getData() {
        // ...
    }
    

    Then call the function and store the result in a variable in the highScore function to use it.

    int highScore() {
        auto weeklyScore = getData();
        // ...
    }