Functions and Scope

Hello, so for my variable 'colorfamily' the value is set by the user in the main function. I cant figure out how to get that value to carry over to be used in another function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
string getColorFileName(string familyName, string colorIndexFileName) {
	fstream colorfile;
	string colorfamily = "";   // This is the variable 
	colorfile.open(baseDir + colorIndexFile);
	string color, fn;
	string fileName;
	cout << colorfamily << "Test" << endl;
	while (!colorfile.eof()) {
		colorfile >> color;
		colorfile >> fn;
		if (color == colorfamily) {
			fileName = fn;
			break;
		}
	}
	colorfile.close();
	//
	return fileName;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <fstream>

std::string getColorFileName( std::string familyName, std::string colorIndexFileName )
{
    std::ifstream file(colorIndexFileName) ; // open the file
    std::string colour, name_of_file ;

    // note: this is canonical; do not loop on eof()
    while( file >> colour >> name_of_file ) if( colour == familyName ) break ;

    return name_of_file ; // return an empty string if not found
}

int main()
{
    std::string colour_family = "something" ;
    std::string file_name = "some path" ;

    // pass colour_family (and file_name) to the function
    std::string colour_file_name = getColorFileName( colour_family, file_name ) ;
}
Topic archived. No new replies allowed.