Monday, May 24, 2010

Visual C++: How do you return multiple types?

I want main() to repeatedly calls a function called getToken().


I want getToken to read the next token in the input file, and then return to main() the token type, the actual string (lexeme) of the token.





The token type is an integer (1, 2, 3, whatever) and the string is, well, a string.





How can I make getToken() return both an int and a string?

Visual C++: How do you return multiple types?
Use somethiing like:





int getToken (char **tokString)


{


int retvalue;


char *str1;





//code in here to assign str1 to the token string and retvalue to token type





*tokString = str1;


return retvalue;


}





Your calling function would look something like this.





char *str; (declare it, don't define it)


int toktype;


toktype = getToken(%26amp;str);





I used to use this all the time in my Visual C++ code (actually replace char with TCHAR). It's a lot better than using a struct.





But watch for memory leaks.





===





You could also make the integer a pointer in the argument, of course.





In fact, you can return as many variables as you want as function arguments, if you do them as pointers. Just be aware of memory leaks (again) and scope.





Hope this helps.
Reply:I don't think template will help u, because string is not a basic data type.


why dont u just read all inputs as string and then in the main (or any function), check if it is string or number. According to result of that check, use atoi(char *) function to get the integer value of the string.
Reply:C++ standard library has a template called "pair".





#include %26lt;utility%26gt;





using namespace std;





pair%26lt;TokenType, string%26gt; getToken() {


....


pair%26lt;TokenType,string%26gt; p(TYPE1,"something");


return p;


}





The contents can be retrieved with data members .first and .second. "pair" is basically a struct, as suggested by previous anwers. Just you do not need to define it yourself.





see http://www.unc.edu/depts/case/pgi/pgC++_...
Reply:read about --templates---....


the solution could be something like that:





template%26lt;class TT%26gt;


TT getToken()


{


TT retValue;


//..........


return retValue;


}





void main()


{


int t = getToken%26lt;int%26gt;();


char c = getToken%26lt;char%26gt;();


//..... goodLuck


}
Reply:Create a struct -





struct Foo


{


int zint;


char* zstr;


};





Then use it like this -





Foo temp;


temp.zint = 1;


temp.zstr = "test";


No comments:

Post a Comment