菜鸟笔记-从一个文件读取日期07/21/2016,转换为July 21,2016并输出到屏幕上

小结:很笨的原始方法

#include<iostream>
#include<fstream>

using namespace std;


int main()
{	
	ifstream file1("text.txt");
	char a[20],ch;
	int i=0;
	while(file1.get(ch)){//文件中读取的数据存入数组 
		cout<<ch;
		a[i]=ch;
		i++;
	}
	file1.close();
	cout<<endl;
	string mon[12]={"Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"};
	int month,day,year;
	int j;
	//cout<<a[1]-'0'<<endl;
	for(j=0;j<i;j++){
		if(a[j]=='/'){
			month=(a[j-1]-'0')+(a[j-2]-'0')*10;
			break;
			//cout<<a[j-1]-'0'<<","<<a[j-2]-'0'<<endl;
		}
			
	}
	//cout<<month<<endl;
	for(int k=j+1;k<i;k++){
		if(a[k]=='/'){
			day=(a[k-1]-'0')+(a[k-2]-'0')*10;
			//cout<<a[k-1]-'0'<<","<<a[k-2]-'0'<<endl;
		}
			
		if(a[k+1]=='\0')
			year=(a[k]-'0')+(a[k-1]-'0')*10+(a[k-2]-'0')*100+(a[k-3]-'0')*1000;
	}
	cout<<mon[month-1]<<" "<<day<<","<<year;
	return 0;
}

找到一个很好的 https://blog.csdn.net/qq_32925781/article/details/79423803 参考

#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;
}
发布了25 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/natures66/article/details/88083195