Search code examples
c++stringvector

Store cout from function as string


I have a function that takes in a vector of integers and outputs them via std::cout.

#include <iostream>
#include <vector>

void final_sol(std::vector<int> list){
    for (int i ; i < list.size() ; i++){
        std::cout << list[i] << " ";
    }
}

int main(){
    std::vector<int> list = {1, 2, 3, 4, 5};
    final_sol(list);
    return 0;
}

However, from this point I would like to have a way to quickly obtain the outputs of final_sol(vector) as a string. One way to do this would be to modify the original function to also create the string. However, I am not interested in modifying final_sol(vector). Is there another way I could store the outputs as a string?


Solution

  • Provide overload:

    void final_sol(std::ostream& out, const std::vector<int>& list){
        for (int i = 0; i < list.size() ; i++){
            out << list[i] << " ";
        }
    }
    
    void final_sol(const std::vector<int>& list){
        final_sol(std::cout, list);
    }
    

    This way you existing calling code will not be impacted - most probably this is what you want: not modifying function signature. Not what you described: not do not modifying implementation of final_sol.

    Then you can do:

    std::ostringstream str;
    final_sol(str, list);
    auto s = str.str()