我正在为一种编程语言编写一个解释器,我用的是一种C++,一种语言,坦率地说,我对此非常陌生。
我试图完成的是将std::string中的特定浮点格式转换为双(或其他)格式。我希望它完全独立于区域设置,并尽可能健壮。
我有两个案子:
.4或4.),但不能同时删除。
我希望它是"C++的方式“来做。我是否可以使用一个函数来指定自定义数字格式(类似于PHP中的date )。
我将非常感谢任何指针或代码片段提供。谢谢!
发布于 2011-10-31 22:59:17
假设您的意思是字符串位于C区域设置中:
template<class T>
std::string tostring(const T& input)
{
stringstream ss;
if (!(ss << input))
throw std::runtime_error("cannot convert!");
return ss.str();
}
template<class T>
void fromstring(const std::string& input, T& output)
{
stringstream ss(input);
if (!(ss >> output) || ss)
throw std::runtime_error("cannot convert!");
}
//Passes output as parameter, in case it's not copiable.
int main() {
float pi = 3.14159f; //pi to string and back
std::string strpi = tostring(pi);
fromstring(strpi, pi);
std::ifstream in("in.txt"); //copies a file through a string
std::string file = tostring(in);
std::ofstream out("out.txt");
fromstring(file, out);
return 0;
}发布于 2011-10-31 23:01:36
整数:它们应该是从0到9的连续数字,有或没有前导减号(不允许加号,允许前导零)
浮点数:带或不带前导减号的整个part.decimal部件,没有任何数千个分隔符.可以省略整个部分或十进制部分(例如.4或4.),但不能两者兼而有之。
这些几乎不是“自定义格式”;它们可以被stringstream (或者,如果您使用BOOST,一个lexical_cast)很好地解析。
#include <iostream>
#include <string>
#include <sstream>
int main( ... ) {
std::string s = "-1.0";
float f = 0;
if( std::stringstream(s) >> f ) {
std::cout << f;
}
else {
std::cout << "No good!";
}
return 0;
}https://stackoverflow.com/questions/7960709
复制相似问题