练习9.50:编写程序处理一个vector<string>
,其元素都表示整型值。计算vector中所有元素之和。修改程序,使之计算表示浮点值的string之和。
答:见练习9.50.cpp
练习9.51:设计一个类,它有三个unsigned成员,分别表示年月和日。为其编写构造函数,接受一个表示日期的string 参数。你的构造函数应该能处理不同数据格式,如Jannuary 1,1900 , 1/1/1900, Jan 1 1900
答:见练习9.51.cpp
练习9.50
/*
*练习9.50
*日期:2015/8/7
*问题描述:编写程序处理一个vector<string>,其元素都表示整型值。计算vector中所有元素之和。修改程序,使之计算表示浮点值的string之和
*功能;
*作者:Nick Feng
*邮箱:nickgreen23@163.com
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> vec ={"1","12","13","6.7","7"};
int sum = 0;
float sum_f = 0.0;
if(!vec.empty())
{
for(auto i = 0; i != vec.size(); ++i)
{
cout << vec[i] << " ";
sum = sum + stoi(vec[i]);
sum_f += stof(vec[i]);
}
cout << endl;
cout << sum << endl;
cout << sum_f << endl;
}
else
{
cout << "May be vector is empty!" << endl;
}
return 0;
}
练习9.51
/*
*练习9.51
*2015/8/7
*问题描述:练习9.51:设计一个类,它有三个unsigned成员,分别表示年月和日。为其编写构造函数,接受一个表示日期的string 参数。你的构造函数应该能处理不同数据格式,如Jannuary 1,1900 , 1/1/1900, Jan 1 1900
*说明:没有做正确性检查,对输入不合理的日期,也能过,这是有待改进的地方,不想写了
*作者:Nick Feng
*邮箱:nickgreen23@163.com
*
*/
#include <iostream>
#include <string>
using namespace std;
class Date{
public:
friend ostream &print(Date &,ostream &);
Date() = default;
Date(string &);
//private:
unsigned month;
unsigned day;
unsigned year;
};
ostream &print( Date &da, ostream &out)
{
out << "Year: " << da.year << endl << "Month: " << da.month << endl << "Day:" << da.day << endl;
}
Date::Date(string &str)
{
string s = ", /"; // 逗号, 空格, 斜杠
auto pos = str.find_first_of(s);
auto pos1 = str.find_last_of(s);
if(pos != string::npos && pos1 != string::npos)
{
string temp = str.substr(0,pos); //取第一个数,即Month
if(temp =="January" || temp == "Jan") //进行Month的格式调整
temp = "1";
else if(temp =="February" || temp == "Feb")
temp = "2";
else if(temp =="March" || temp == "Mar")
temp = "3";
else if(temp == "April" || temp == "Apr")
temp = "4";
else if(temp == "May")
temp = "5";
else if(temp == "June" || temp == "Jun")
temp = "6";
else if(temp == "July" || temp == "Jul")
temp = "7";
else if(temp == "August" || temp == "Aug")
temp = "8";
else if(temp == "September" || temp =="Sep")
temp = "9";
else if(temp == "October" || temp == "Oct")
temp = "10";
else if(temp == "November" || temp == "Nov")
temp = "11";
else if(temp == "December" || temp == "Dec")
temp = "12";
month = stoul(temp);
day = stoul(str.substr(pos+1,pos1-pos-1)); //第二个数,日
year = stoul(str.substr(pos1+1)); //第三个数,年
}
}
int main()
{
string s = ", /";
string str = "May,30 1990";
cout << str << endl;
Date da(str);
print(da,cout);
return 0;
}