Hi there, I’m fairly new a c++ and am having trouble figuring out how to use a returned function variable.

Here’s my code

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector> 
#include <algorithm> 
#include <iterator> 
using namespace std;

std::string OMPS (char const* path) 
    //set string array length
    string line[1000];

    //loop counter
    int n = 0;

    //set text file to read
    ifstream myfile(path);

    if (myfile.is_open())
            while ( myfile.good() )
                getline (myfile,line[n]);
                cout << line[n] << endl;

                //move on to next line


    else cout << "Unable to open file"; 

    string x = line[3];
    cout << x << endl;
    return x;

int main()

    cout << OMPS <<endl;

    return 0;

When i print x from the OMPS function it give the correct output which is an entry in the line array
(6522 2 0 44 789 325 2.001 26.33 65.22 3.11)

But when i call it from main it just gives me the memory address, as you can probably tell i don't really understand pointers!

Ideally i would like to put each "line" into an array and pass the whole lot to main, but that seems like a whole world of pain!

Any Ideas

Many Thanks in advance


4 Years
Discussion Span
Last Post by phorce

i had not tried that and that has worked! I guess i wasn't initialising anything to put the output into.

Thanks alot for your help, i do have one more question though (sorry), on line 40 of the above code i set x to be what ever is in the 3rd entry on the array "string x = line[3];"

My question is; how do i pass the whole array to the main function?

if i get rid of the [3] or leave it empty [] i get the following error out of visual studio:

cannot convert from 'std::string [1000]' to 'std::basic_string<_Elem,_Traits,_Ax>

Thanks for all your help so far.





Look at this example:

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

string* returnString(const char* filename) {
 string* names = new string[3];
 names[0] = "Hello";
 names[1] = "World";
 names[2] = "huuhaa"; 

 return names;
int main(int argc, char *argv[]) {

    string* names = returnString("file.txt");

    for(unsigned i=0; (i < 3); i++)
        cout << names[i] << endl;


Or use a vector :) You've included it! Hope this helps though


No problem :)

If this has been solved, please mark it so and give repo to those who helped you..

Thanks :)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.