E
eric
Dear advanced C++ programers:
I copied a piece simple template and stringstream program from book
(c++ cookbook) on chapter 3, section 5: Parsing a String Containing a
Number in Scientific Notation.
-------------------------------------------------------------------------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//double sciToDub(const string& str) {
template<typename T>
T strToNum(const string& str) {
stringstream ss(str);
T tmp;
ss >> tmp;
// double d = 0;
// ss >> d;
if (ss.fail()){
string s = "Unable to format ";
s += str;
s += " as a number!";
throw(s);
}
return(tmp);
}
int main() {
try {
/*
cout << sciToDub("1.23456789e5") << endl;
cout << sciToDub("6.02987654e-5") << endl;
cout << sciToDub("asdf") << endl;
*/
double d = strToNum<double>("7.0"); cout << d << endl;
float f = strToNum<float>("7.0"); cout << f << endl;
int i = strToNum<int>("7.0"); cout << i << endl;
char c = strToNum<char>("7.0"); cout << c << endl;
}
catch (string& e) {
cerr << "Whoops: " << e << endl;
}
}
------------------------------------------------------------------------------------------------------
on my test of g++,
all 4 show 7
why , especially first 2 (double and float)?
thanks your help in advance a lot
Eric
I copied a piece simple template and stringstream program from book
(c++ cookbook) on chapter 3, section 5: Parsing a String Containing a
Number in Scientific Notation.
-------------------------------------------------------------------------------------------------------------------------------
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//double sciToDub(const string& str) {
template<typename T>
T strToNum(const string& str) {
stringstream ss(str);
T tmp;
ss >> tmp;
// double d = 0;
// ss >> d;
if (ss.fail()){
string s = "Unable to format ";
s += str;
s += " as a number!";
throw(s);
}
return(tmp);
}
int main() {
try {
/*
cout << sciToDub("1.23456789e5") << endl;
cout << sciToDub("6.02987654e-5") << endl;
cout << sciToDub("asdf") << endl;
*/
double d = strToNum<double>("7.0"); cout << d << endl;
float f = strToNum<float>("7.0"); cout << f << endl;
int i = strToNum<int>("7.0"); cout << i << endl;
char c = strToNum<char>("7.0"); cout << c << endl;
}
catch (string& e) {
cerr << "Whoops: " << e << endl;
}
}
------------------------------------------------------------------------------------------------------
on my test of g++,
all 4 show 7
why , especially first 2 (double and float)?
thanks your help in advance a lot
Eric