Description:
根据一些日期,以及日期上所做的标记,按条件统计其天数。
Input:
输入数据含有不多于50个的具有格式“Mon.DD YYYY”的日期,有些日期后面可能标有*,每个日期占一行。
Output:
统计任何月份中凡是25号的日期数,如果25号这一天后面标有*,则该天应加倍计算.
Sample Input:
0ct.25 2003
0ct.26 2003
Sep.12 2003*
Juy. 25 2002*
Sample Output:
3
代码一:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int count = 0;
string date;
while (getline(cin, date)) {
int day = stoi(date.substr(4, 2));
if (day == 25) {
count++;
if (date.back() == '*') {
count++;
}
}
}
cout << count << endl;
return 0;
}
运行结果:
1.直接回车两次:
会报错,并且返回值为应该输出结果
2.利用Ctrl和Z输入两次
结果正确了,但是输入与题干要求不符合
对代码进行改进:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
int count = 0;
string date;
while (getline(cin, date)) {
if (date == "")break;
int day = stoi(date.substr(4, 2));
if (day == 25) {
count++;
if (date.back() == '*') {
count++;
}
}
}
cout << count << endl;
return 0;
}
直接回车两次
改进之处:
添加了一行: if (date == "")break;
可以使输入条件进行限制与规范;
注意:
getline函数需要进行两次回车可以输出,多用于无法判断终止条件的时候使用;
输入数据时,月份后没有空格,只有日期与年份之间有空格,不要私自加空格,不然会无法调用函数,一直输不出正确结果,卡在这卡了好久。