//string和数值之间的转换
to_string(val); //val可以是任何算数类型。
stoi(s,p,b); //s:待转换字符
stol(s,p,b); //p: size_t 类型指针,表示string字符串中第一个非数值字符的下标。
stoul(s,p,b); //b:默认10进制。
stoll(s,p,b);
stoull(s,p,b);
stof(s,p,b);
stod(s,p,b);
stold(s,p,b);
练习9.50:编写程序处理一个vector<string>
,其元素都表示整型值。计算vector中所有元素之和。修改程序,使之计算表示浮点值的string之和。
整型值
vector<string> v1= {"12","13","14","15","16"};
int sum = 0;
for(auto i=0;i<v1.size();i++){
sum += stoi(v1[i]);
}
cout<<sum<<endl;
浮点值
vector<string> v1 = { "12.1", "13.1", "14.1", "15.1", "16.1" };
float sum = 0;
for (auto i = 0; i<v1.size(); i++){
sum += stof(v1[i]);
}
cout << sum << endl;
string s = "314.15926";
size_t nu;
//int a = stoi(s.substr(s.find_first_of("+-.0123456789")), &nu);
int a = stoi(s, &nu);
以上代码:nu运行后的值为3因为314.15下标为3的地方是 ‘.’ 出现在小标3的位置。
练习9.51:设计一个类,它有三个unsigned成员,分别表示年月和日。为其编写构造函数,接受一个表示日期的string 参数。你的构造函数应该能处理不同数据格式,如Jannuary 1,1900 , 1/1/1900, Jan 1 1900
class Data{
public:
unsigned int year;
unsigned int month;
unsigned int day;
Data(string str_data){
string temp(" ,/");
string::size_type pos1 = str_data.find_first_of(temp, 0);
string subs = str_data.substr(0, pos1);
if (subs == "January" || subs == "Jan") month = 1;
if (subs == "February" || subs == "Feb") month = 2;
string::size_type pos2 = str_data.find_first_of(temp, pos1 + 1);
subs = str_data.substr(pos1 + 1, pos2 - pos1 + 1);
day = stoi(subs);
string::size_type pos3 = str_data.find_first_of(temp, pos2 + 1);
if (pos3 == string::npos) subs = str_data.substr(pos2 + 1);
else subs = str_data.substr(pos3 + 1);
year = stoi(subs);
}
};
代码中string::size_type pos2 = str_data.find_first_of(temp, pos1 + 1);这句话找到的是在字符串str_data中的下标位置,而不是从pos1+1算起走的位置。