Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I use template or auto keyword in cpp to create a variable that i can use with std:: cin to get a value from user?

this line of code is wrong and won’t compile but i am wondering if it can be fixed.

#include <iostream>

template <typename T>

auto getValue()
{
    std::cout << "Enter an integral value: ";
    T value{};
    std::cin >> value;
    // I would do input handing later
    return value;
}

int main()
{
    auto value1{getValue()};
    std::cout << value1 << '\n';
}

please point out if there is a way to make it possible or if it is not possible then why?

thank you.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to receive an integral value from the user and create a variable depending on the value that they entered.

for example
if they entered
56
then an integer variable will be created.
and if they entered
56.78
then a double variable will be created since it is a lateral.

>Solution :

Types are fixed at compile time so your code can’t work. If you really need to do this then there are a few approaches.

  1. The javascript approach of just using double everywhere, a double can hold 53 bit integers without losing precision.
  2. Return a std::variant

Option 2 could look something like this:

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

std::optional<int> parseInt(const std::string& str)
{
    try
    {
        size_t pos;
        int value = std::stoi(str, &pos);
        if (pos == str.size())
        {
            return value;
        }
    }
    catch (std::exception&)
    {
    }
    return {};
}

std::optional<double> parseDouble(const std::string& str)
{
    try
    {
        size_t pos;
        double value = std::stod(str, &pos);
        if (pos == str.size())
        {
            return value;
        }
    }
    catch (std::exception&)
    {
    }
    return {};
}
std::variant<int, double> getValue()
{
  while (true)
  {
    std::cout << "Enter a numerical value: ";
    std::string str;
    std::getline(std::cin, str);
    auto i = parseInt(str);
    if (i)
    {
        return *i;
    }
    auto d = parseDouble(str);
    if (d)
    {
        return *d;
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading