+ 1

In c++ how to declare variable of a type which can hold either integer or character?

Depending upon users input..

14th Jul 2021, 6:22 PM
pavan
pavan - avatar
3 Antworten
+ 5
The std::variant type is perfect for such a case. It can hold any one of the types you pass as type paramters https://en.cppreference.com/w/cpp/utility/variant Example: ``` std::variant<int, char> v; v = 10; // 'v' now holds int v = 'a'; // 'v' now holds char ```
14th Jul 2021, 7:53 PM
XXX
XXX - avatar
+ 1
You can either use unions or a class with a constructor for int and one for char
14th Jul 2021, 6:27 PM
Angelo
Angelo - avatar
+ 1
Maybe you could string input and then try to parse to integer...
14th Jul 2021, 7:38 PM
Lisa
Lisa - avatar