Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to template type

Tags:

c++

I'm writing program in c++ and today I faced following problem, and I wonder if someone could help or explain how to solve it. Basically I have deal with template class and one of the method should take an input from user as a string value ,convert it to template value and return. Here is how code looks like :

T HashTable<T>::insertValue()
{
    T value;
    string str;

    cout << "Insert value please" << endl;
    getline(cin,str);
    stringstream convert(str);
    convert >> value;

    return value;
} 

it works perfectly fine until I input string- if I enter the whole sentence -after conversion the part after first space is lost. is there any way to avoid that?

like image 656
aldebaran Avatar asked Oct 23 '13 15:10

aldebaran


Video Answer


1 Answers

Something like this?

template<typename T>
T getline_as( std::istream& s );

template<>
std::string getline_as<std::string>( std::istream& s )
{
    std::string str;
    std::getline(s,str);
    return str;
} 

template<typename T>
T getline_as( std::istream& s )
{
    std::stringstream convert(getline_as<std::string>(s));

    T value;
    convert >> value;
    return value;
}

T HashTable<T>::insertValue()
{
    cout << "Insert value please" << endl;
    return getline_as<T>(cin);
}
like image 115
Ben Voigt Avatar answered Oct 12 '22 11:10

Ben Voigt