I want implement a function that convert std::string to any numeric type and I come with this
#include <iostream>
#include <string>
#include <sstream>
template<typename T>
T str2num(const std::string &str) {
std::istringstream iss(str);
T t;
iss >> t;
return t;
}
int main() {
std::cout << str2num<uint64_t>("12345") << std::endl;
std::cout << str2num<uint32_t>("12345") << std::endl;
std::cout << str2num<uint16_t>("12345") << std::endl;
std::cout << str2num<uint8_t>("123") << std::endl;
return 0;
}
But not everything is fine.
The last line output 1
instead of 123.
Why did this happen and how to make it right?