Reputation:
I have been trying to make a Convert.To command like in C# in C++ but I dont want to do it like "IntToString" Instead I want to make it like "ToString" just like in C#. I was wondering how can I know the format of the parameter given inside the function? Or is there any other way to do this?
#include <iostream>
#include <sstream>
class converting {
public:
std::string Int32ToString(int x) {
std::stringstream asd;
asd << x;
std::string cnvrtd;
asd >> cnvrtd;
return cnvrtd;
}
int StringToInt32(std::string x) {
std::stringstream asdf(x);
int cnvrtd;
asdf >> cnvrtd;
return cnvrtd;
}
};
int main() {
converting Convert;
std::cout << "This is for a test. Avaiable options are:" << std::endl << "StringToInt32" << std::endl << "Int32ToString" << std::endl;
std::string firstinput;
std::cin >> firstinput;
if (firstinput == "StringToInt32") {
std::string input;
int result;
std::cin >> input;
result = Convert.StringToInt32(input);
std::cout << result;
return 0;
}
else if (firstinput == "Int32ToString") {
int input;
std::string result;
std::cin >> input;
result = Convert.Int32ToString(input);
std::cout << result;
return 0;
}
else {
std::cout << "Please enter a valid input";
return 0;
}
}
Upvotes: 0
Views: 228
Reputation: 28
When you say - Format of the parameter given inside the function, do you mean, how do you know the data type of the parameter. If that's the case, you will have to write functions for all the data types for which you want to support conversion, inside your Converting class with same function name, this is called function overloading in C++. e.g.
std::string convert (int n){}
std::string convert (float n){}
std::string convert (double n){}
When you will invoke this convert function compiler will choose appropriate overloaded function according to the data type.
However there is smaller way to achieve the same functionality by writing a template function like
template<class Dt>
std::string Convert (Dt n){
return std::to_string(n);
}
Hope I am not missing considering any limitations if you have mentioned.
Upvotes: 1