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
                n++;
            }

            myfile.close();
      }

    else cout << "Unable to open file"; 

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

int main()
{   

    OMPS("test.txt");
    cout << OMPS <<endl;

    system("pause");
    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

Al

Have you tried this ?

 string text;

 text = OMPS("test.txt");

 cout<<"\n Output is "<< text;

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.

Cheers

Al

Hello,

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

Thats great, thats for all your help

Al

No problem :)

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

Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.