int main(int argc, char* argv[])
{
string file_name;
cout<<"please input the fileName:"<<" ";
cin>>file_name;
ifstream infile(file_name.c_str());
if(!infile){
cerr<<"unable to open input file: "
<<file_name<<endl;
return -1;
}
string str;
while (getline(infile,str,\n)){
if(str!="0")
if(str!="END")
s_dnum.push_back(str);
}
for(int ix=0;ix<s_dnum.size();++ix)
{
cout<<s_dnum[ix]<<endl;}
cout<<s_dnum.size()<<endl;
}
怎么把s_dnum中的String转换为Double?
double x=atof(s)
void ConvertDoubleString(double doubleVal)
{
String* stringVal;
// A conversion from Double to String* cannot overflow.
stringVal = System::Convert::ToString(doubleVal);
System::Console::WriteLine(S" {0} as a String* is: {1}",
__box(doubleVal), stringVal);
try {
doubleVal = System::Convert::ToDouble(stringVal);
System::Console::WriteLine(S" {0} as a double is: {1}",
stringVal, __box(doubleVal));
} catch (System::OverflowException*) {
System::Console::WriteLine(S"Conversion from String*-to-double overflowed.");
} catch (System::FormatException*) {
System::Console::WriteLine(S"The String* was not formatted as a double.");
} catch (System::ArgumentException*) {
System::Console::WriteLine(S"The String* pointed to null.");
}
}
这是我以前在这里收集的一些代码,算是比较经典的。您可以参考下!
#include <iostream>//字符串变整型数#include<stdlib.h> atoi() atol()等函数!
#include <string>
using namespace std;
int main()
{
string str = "123";
long i;
const char *cs;
cs = str.c_str();//string类型变为char *类型
i = atol(cs) + 1;//char *指向字符串变为long类型
cout << cs << endl;
cout << "i = " << i << endl;
}
#include <cstdlib>
#include <cstdio>
//using namespace std;
int main(void)
{
char *string = "87654321", *endptr;
long lnumber;
/* strtol 把string转换成long*/
lnumber = strtol(string, &endptr, 10);
printf("string = %s long = %ld\n", string, lnumber);
return 0;
}
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
#include <iomanip>
using namespace std;
using namespace boost;
int main()
{
double b=0;
string str="12345.6789";
cout<<setprecision(10)<<showpoint;//设置输出精度和小数
try
{
b=lexical_cast<double>(str); //转换操做
}
catch(bad_lexical_cast& e)
{
e.what();
}
cout<<b<<endl;
return 0;
}
使用boost 库很简单,而且提供了异常机制,也可义用标准库中的字符串流来实现
template<class _Elem,class _Traits,class _Alloc>class basic_stringstream: public basic_iostream<_Elem, _Traits>
来实现。
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
int main()
{
string str="12345.6789";
basic_stringstream<char,char_traits<char>,std::allocator<char> > stream;
stream<<str;
double h;
stream>>h;
cout<<h;
}
这样没有异常机制,无法控制失败情况。而w_char(宽字符)的也要写一个.
atol() atof 之类的就不要用了,不是 c++ 安全的
#include <sstream>
...
string str;
...
double dValue;
...
stringstream ss;
ss << str;
ss >> dValue;
现在dValue就是了,使用stringstream可以很方便的完成类似的转换,可以替代sprintf,CString::format等等原来用格式化字符串完成的功能,以及十六进制,八进制,十进制之间的转换等等。
#include <sstream>
template <typename T>
T to_numeral(const std::string& src)
{
T dest;
std::stringstream ss;
ss << src;
ss >> dest;
return dest;
}