2017年复试程序设计题

2017年

题目

格式转换,从一个文件中读取日期07/21/2016,转换为以下格式July 21,2016并输出到屏幕上

方法一:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;

int main(){

    ifstream is("/Users/.../MyDate.txt");

    if (!is){
        cerr << "File cannot be opened!" << endl;
        exit(EXIT_FAILURE);
    }

    string myMonth[13] = {"","Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"};
    string  line;
    int month;
    int day;
    int year;

    while (is >> line) {
        month = stoi(line.substr(0,2));
        day = stoi(line.substr(3,2));
        year = stoi(line.substr(6,4));

        cout << setw(4) << left  << setfill(' ') << myMonth[month] << " ";
        cout << setw(2) << right << setfill('0') << day << "," << year << endl;
    }

    return 0;
}

运行结果:
这里写图片描述

值得注意的是,setfill(‘0’)函数设置填充字符过后是会一直生效的,所以要在输出月份之前添加一句setfill(’ ‘)以保证格式统一。

方法二:

当然也可以这么玩:

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;

int main(){

    ifstream is("/Users/.../MyDate.txt");
    if (!is) {
        cerr << "File cannot be opened!" << endl;
        exit(EXIT_FAILURE);
    }

    string temp;
    string mon[13] = {"","Jan","Feb","Mar","Apr","May","June","July","Aug","Sept","Oct","Nov","Dec"};
    int month,day,year;
    size_t Pos_1,Pos_2;

    while (is >> temp) {
        Pos_1 = temp.find("/");
        Pos_2 = temp.find_last_of("/");

        month = stoi(temp.substr(0,Pos_1));
        day = stoi(temp.substr(Pos_1 + 1,Pos_2 - Pos_1 - 1));
        year = stoi(temp.substr(Pos_2 + 1));

        cout << setw(4) << left << setfill(' ') << mon[month] << " " << setw(2) << right << setfill('0') << day << "," << year << endl;
    }

    return 0;
}

法二更加通用化。

猜你喜欢

转载自blog.csdn.net/qq_32925781/article/details/79423803
今日推荐