553C++笔试笔记2017

1.从一个文件中读取日期07/21/2016,以以下格式输出July 21,2016。

方法1.

#include <fstream>
#include <iostream>
#include<string>
#include <iomanip>
using namespace std;
int main() {
	ifstream is("D:/word.txt");
	if (!is) {
		cerr << "file cannot be opened!";
		exit(EXIT_FAILURE);
	}
	string Mmonth[13] = {"","Jan","Feb","Mar","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(' ') << Mmonth[month] << " ";
		cout << setw(2) << right << setfill('0') << day << "," << year << endl;
	}
	return 0;
}

创建输入流,从文件输入到字符串line,其中每次is传输的字符串以空格为分割。 

方法2.

#include <fstream>
#include <iostream>
#include<string>
#include <iomanip>
using namespace std;
int main() {
	ifstream is("D:/word.txt");
	if (!is) {
		cerr << "file cannot be opened!";
		exit(EXIT_FAILURE);
	}
	string Mmonth[13] = { "","Jan","Feb","Mar","June","July","Aug","Sept","Oct","Nov","Dec" };
	string line;
	int month;
	int day;
	int year;
	while (is >> line) {
		size_t pos1 = line.find("/");
		size_t pos2 = line.find_last_of("/");
		month = stoi(line.substr(0, pos1));
		day = stoi(line.substr(pos1 + 1, pos2-pos1-1));
		year = stoi(line.substr(pos2 + 1));
		cout << setw(4) << left << setfill(' ') << Mmonth[month] << " ";
		cout << setw(2) << right << setfill('0') << day << "," << year << endl;
	}
	return 0;
}

理论上来讲方法2更加通用,因为分割的我位置常常不是固定的而格式却是有迹可循的。

总结一下字符串解析通常会用到的两种方法:

当涉及到需要循环判断或者处理的时候,用substr和erase组合或者strtok都是可以的。

当我们处理的字符串是字符数组形式的时候,我们使用strtok

char a[MAXSIZE];
//初始化a
char* s = strtok_s(a, " ", &t);
	while (s) {
		操作
		s = strtok_s(NULL, " ", &t);
	}

当我们处理的字符串是string类型的时候,我们使用substr、erase和find等等string类函数的组合。

	word = a.substr(0, a.find(" "));
	while(!a.empty()){
		if (a.find(" ") == a.npos) {
				//操作
				break;
		}
		/*word = a.substr(0, a.find(" "));*/
		//操作
		a.erase(0, a.find(" ") + 1);
		word = a.substr(0, a.find(" "));
	}

 注意,判断结束条件不能少,一个字符串的时候后面是没有空格的。

到此为止好像553所有的以编程为全部题型的试卷都复习完了,总体看上去后期竟然连继承和多态都没有了,不知道是没有找到资源还是什么情况。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值