[求助]在C++中可以从文本文件中读其他类型数据吗
文本文件存放的是字符型数据,但请问可不可以通过类型转换将其转换成整型或浮点型输出?如果能的话应该怎么做?最好可以举下例子(编个程序段),谢谢各位了[align=right][color=#000066][此贴子已经被作者于2007-8-9 19:46:27编辑过][/color][/align]
<P>如果你是用C++ BUILDER的话<BR></P>
<P>如果你是用C++ BUILDER的话<BR></P>
<P>std::ifstream readline("xxx.txt")<BR>std::string textline;<BR>while(getline(readline,textline,'\n')){<BR> AnsiString convert = textline.c_str();<BR> double _float = covert.ToDouble();<BR> int _float = covert.ToInt();<BR>}</P>
<P>以下这个是我自己编写的<BR></P>
<P>//---------------------------------------------------------------------------<BR>//字符串转浮点<BR>double Atof(const char* buffer)<BR>{<BR> if( Isdigit(buffer) == false ) return 0;<BR> std::string strMoney(buffer);<BR> double fsum = 0.0;<BR> if( buffer[0] == '-')<BR> {<BR> for(std::size_t index = 1; index < strMoney.length(); ++index)<BR> {<BR> if( strMoney[index] != '.'){<BR> fsum = fsum * 10 + (strMoney[index]-48);<BR> }<BR> }<BR> fsum *= -1;<BR> }<BR> else{<BR> for(std::size_t index = 0; index < strMoney.length(); ++index)<BR> {<BR> if( strMoney[index] != '.'){<BR> fsum = fsum * 10 + (strMoney[index]-48);<BR> }<BR> }<BR> }<BR> int nPos = 0;<BR> if( (nPos = strMoney.find_first_of('.')) != std::string::npos)<BR> {<BR> int nCount = strMoney.length()- nPos;<BR> for( int index = 0; index < nCount-1; ++index)<BR> {<BR> fsum *= 0.1;<BR> }<BR> }<BR> return fsum;<BR>}<BR>//-------------------------------------------------------------------------------<BR>// 判断是否数字<BR>bool Isdigit(const char* str)<BR>{<BR> std::string strNum(str);</P>
<P> if( strNum == "" || strNum == " " || strNum[0]== '.'){<BR> return false;<BR> }</P>
<P> int count = 0;<BR> string::iterator it = strNum.begin();<BR> for(; it!= strNum.end(); ++it)<BR> {<BR> if( (*it <'0'&& *it != '.' && *it != '-') || *it > '9'){<BR> return false;<BR> }<BR> else if( *it == '0' && it == strNum.begin() )<BR> {<BR> if(*(++it) != '.'){<BR> return false;<BR> }<BR> --it;<BR> }<BR> else if( *it == '.' )<BR> {<BR> count++;<BR> }<BR> else if( *it == '-' && it != strNum.begin() )<BR> {<BR> return false;<BR> }<BR> }<BR> if( count > 1){<BR> return false;<BR> }<BR> return true;<BR>}</P>
页:
[1]
