C++primer 9.5.5节练习

本文通过两个示例展示了如何使用C++标准库函数将字符串转换为整数和浮点数,并提供了一个日期类的构造函数从字符串中解析日期。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

练习9.50

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     int sum = 0;
10     int num;
11     vector<string> vec{ "12","23","1","34","13","99" };
12     for (auto it = vec.begin(); it != vec.end(); ++it)
13     {
14         num = stoi(*it);
15         sum += num;
16     }
17     cout << sum << endl;
18     system("pause");
19     return 0;
20 }

修改后

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     double sum = 0;
10     double num;
11     vector<string> vec{ "12.0","23.9","1.0","34.0","13.0","99.0" };
12     for (auto it = vec.begin(); it != vec.end(); ++it)
13     {
14         num = stod(*it);
15         sum += num;
16     }
17     cout << sum << endl;
18     system("pause");
19     return 0;
20 }

练习9.51

比较麻烦,截取其中一个做做实验,关键是掌握各种函数的用法

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 
 5 using namespace std;
 6 
 7 class date {
 8     friend ostream &print(ostream &os, date &d);
 9 public:
10     date(unsigned y, unsigned m, unsigned d) : years(y), month(m),days(d){}
11     date() : date(1990,1,1) {}
12     date(string &s);
13     
14 private:
15     unsigned years;
16     unsigned month;
17     unsigned days;
18 };
19 
20 ostream &print(ostream &os, date &d);
21 
22 int main()
23 {
24     string s{ "1/1/1990" };
25     date d1(s);
26     print(cout, d1);
27     system("pause");
28     return 0;
29 }
30 
31 date::date(string &s)
32 {
33     days = stoi(s.substr(0, s.find_first_of('/') - 0));
34     month = stoi(s.substr(s.find_first_of('/') + 1, s.find_last_of('/') - s.find_first_of('/') -1));
35     years = stoi(s.substr(s.find_last_of('/') + 1));
36 }
37 
38 ostream & print(ostream & os, date & d)
39 {
40     os << d.years << " " << d.month << " " << d.days;
41     return os;
42     // TODO: 在此处插入 return 语句
43 }

 

转载于:https://www.cnblogs.com/wuyinfenghappy/p/7348082.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值