Home > Net >  Is there a way to create a data type that can holds both integers and strings in C ?
Is there a way to create a data type that can holds both integers and strings in C ?

Time:08-15

Is there a way to create a data type that can holds both integers and strings in C ?

For example, create a data type with name sti that I can define both integers and strings variables with it:

sti a = 10; //this is integer
sti b = "Hello"; //and this is string

CodePudding user response:

You can use std::variant to achieve this which is C 17 feature. Refer this link to know more.

Following is code sample:

#include <iostream>
#include <variant>
#include <string>

int main()
{
    using sti = std::variant<int, std::string>;
    sti a = 10;
    sti b = "Hello";
    std::cout<<std::get<int>(a) <<std::endl;
    std::cout<<std::get<std::string>(b) <<std::endl;
    return 0;
}

CodePudding user response:

You could use something like this:

struct Sti
{
    int m_number;
    std::string m_number_as_string;

    Sti(int number)
    {
        m_number = number;
        m_number_as_string = std::to_string(number);
    }
    Sti(const std::string& s)
    {
        m_number_as_string = s;
        m_number = std::stoi(s);
    }
};

The above example is one of many possible implementations.
The missing methods are an exercise for the OP or reader.

  •  Tags:  
  • c
  • Related