How to cout a vector from an outside function?

73 views Asked by At

I am trying to write some code where I take each digit of a number, via an outisde function digitSep(), and place it into a vector, in this case vector<int> digits;.

Any idea why I cannot cout << digits[i] or cout << digits.at(i) in a for loop?


std::vector<int> digitSep(int d) {
    
    vector<int> digits;

    int right_digit;              //declare rightmost digit 

    while (d > 0) {
    right_digit = d % 10;         //gives us rightmost digit (i.e. 107,623 would give us '3') 
    d = (d - right_digit) / 10;    //chops out the rightmost digit, giving us a new number
    digits.push_back(right_digit);
    
    }
    return digits;               ///returns us a vector of digits 
}

int main() {
    
    //inputs
    int n; 
    cin >> n; 
    
    vector<int> digitSep(n);   //call the function here with user input n above 
    for (int i = 0; i < digitSep.size(); i++) {
        cout << digits[i] << endl;       ////This is the line that won't work for some reason
    }
    return 0;
}
2

There are 2 answers

0
cigien On

This line:

vector<int> digitSep(n);

doesn't call the function called digitSep. You need to do:

vector<int> digits = digitSep(n); 

And then in the for loop, you have to do:

for (int i = 0; i < digits.size(); i++) {
    cout << digits[i] << endl;   
}

or simply:

for (int i : digits) {
    cout << i << endl;    
}
0
dgrandm On

There are two issues here

  1. vector<int> digitSep(n); is a constructor call, initializing vector containing n elements each initialized to zero.
  2. Main function knows nothing about variable vector<int> digits; since it is in local scope of std::vector<int> digitSep(int d) function