Utilizing a file created from a function.

Hey guys so this is my function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string testGet()
{
	string File1 = "";
	string File2;
	ifstream inFile;
	ofstream ouFile;

	cout << "Name of file blah: ";
	getline(cin, File1);

	inFile.open(File1);
	if (!inFile.is_open())
	{
	ouFile.open(File1)
	}
	File2 = File1;
	return File2;
}


Basically I want the name of the file the user inputs to be assigned to a string(File2) and I want that string (File2) to be useable in int Main().

Whenever I test cout << File2; in Main(), its empty.

I have also declared the string File2 in int Main() (I know that variables are different in Main and Functions) but I want to know if its possible for me to use the string in Main.
Last edited on
In main(), make sure you assign the return value of the function to the File2 string.

 
File2 = testGet();
Last edited on
Added a semicolon on line 14 to make it compile. Depending on your version of c++ you may or may not have to convert to c-strings when opening files. Otherwise it seemed to run OK as below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream>
#include<fstream>
using namespace std;


string testGet()
{
        string File1 = "";
        string File2;
        ifstream inFile;
        ofstream ouFile;

        cout << "Name of file blah: ";
        getline(cin, File1);

        inFile.open(File1.c_str());   // added .c_str()
        if (!inFile.is_open())
        {
        ouFile.open(File1.c_str());   // added semicolon (and .c_str())
        }
        File2 = File1;
        return File2;
}


int main()
{
   cout << "Result is [" << testGet() << "]" << endl;
   return 0;
}
Thanks a bunch Peter!!

I swear the simplest of mistakes in c++ give me the biggest headache hehe.
Topic archived. No new replies allowed.