对string作了一些扩展,包括string转化为int、string转化为double、string转化为bool、打印系统当前时间。但没有解决数据溢出的问题,请大神帮忙解决!
//头文件/*part of interface about string; *it follow the function simply ,no complex situation exist; *so it should be modify before you use it; *overflow problem is need to be solved; */#ifndef FSTRING#define FSTRING#include#include #include using namespace std;//declareextern bool stringToBoolValid;extern bool stringToIntValid;extern bool stringToDoubleValid;//split the string with delim,default delim is ' 'bool split(vector & ,const string str,const char delim=' ');//convert string to intint stringToInt(const string& );//convert string to doubledouble stringToDouble(const string& );//convert string to boolbool stringToBool(const string& );//print current time of this systembool printSystemTime(ostream& output=cout);//delete spacevoid deleteSpace(string& str);
#endif //FSTRING
//源文件#include "fstring.h"#include#include //definitionbool stringToBoolValid=true;bool stringToIntValid=true;bool stringToDoubleValid=true;//分割字符串函数bool split(vector & vecStr,const string str,const char delim){//如果所需要要转化的字符串为空,则直接返回 if(str.empty()) return false; size_t i=0; string subStr; subStr.clear(); while(i '9') { stringToIntValid=false; returnInt=0; return returnInt; } returnInt=returnInt*10+str[i]-'0'; }//如果只有一个正号或负号,输出也是零 if(flagPlusMinus) returnInt*=(-1); return returnInt;}double stringToDouble(const string& str)//转化成浮点数{ if(str.empty()) { stringToDoubleValid=false; return 0; } double returnDouble(0); size_t i=0; size_t flag=2000; int NumPoint=0;//小数点出现次数 int decimalNum(0); bool flagPlusMinus=0; if(str[0]=='+') { i++; } else if(str[0]=='-') { i++; flagPlusMinus=1; } for(;i 1) { stringToDoubleValid=true; returnDouble=0; return returnDouble; } flag=i; continue; } else if(str[i]<'0' || str[i]>'9') { stringToDoubleValid=true; returnDouble=0; return returnDouble; } if(i>flag) { decimalNum++; } returnDouble=returnDouble*10+str[i]-'0'; } for(int t=0;t 1 || str.empty()) { stringToBoolValid=false; return 0; } if(str=="1") return 1; else return 0; }bool printSystemTime(ostream& output){ time_t currentTime=time(0); struct tm* currentTimeStruct=localtime(¤tTime); output<<"系统当前时间:"<<1900+currentTimeStruct->tm_year<<"."<< currentTimeStruct->tm_mon+1<<"."< tm_mday<<" "<< currentTimeStruct->tm_hour<<":"< tm_min<<":"<< currentTimeStruct->tm_sec<
void deleteSpace(string& str){//删除表达式中的空格 string::iterator iter = str.begin(); while (iter != str.end()) {//注意删除后,迭代器指向被删除元素的下一个元素 if (*iter == ' ') { iter = str.erase(iter); } else iter++; }}