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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With