C++ ifstream、sstream按行读取txt文件中的内容,并按特定字符分割,不用strtok

C++ ifstream、sstream按行读取txt文件中的内容,并按特定字符分割,不用strtok

一、预备知识:
主要用到:
1、getline(ifstream in, string line);
将文件in中的数据按行读取到line中
2、getline(stringstream ss,string tmp,const char ch);
将输入字符串流ss中的字符,按ch分割开,依次存入tmp中,直至ss读完。
其中,
stringstream :头文件sstream.h
ifstream :头文件fstream.h
string:头文件string.h

二:实例
1、分割存储固定为3列的小数文件
sstream_fstream.txt文件:
12.34 -3.21 90.34
23 22.1 89.32
100.01 22.78 -9.345
代码:

struct point{
	double x, y, z;
	friend ostream& operator<<(ostream& os, const point p){
		os << "(" << p.x << "," << p.y << "," << p.z << ")";
		return os;
	}
};
void test7(){
	cout << "-----------test7----------- " << endl;
	ifstream in("sstream_fstream.txt");
	string line;
	while (getline(in, line)){//将in文件中的每一行字符读入到string line中
		stringstream ss(line);//使用string初始化stringstream
		point p;
		while (ss >> p.x >> p.y >> p.z){}//由于固定为三列。所以可以这样读取,stringstream 默认按空格分割字符串
		cout << p << endl;
	}
}

2、分割多行文件中每行用空格隔开的字符串,每行包含的小数数字个数不同
sstream_fstream1.txt文件:
12.34 -3.21 90.34
23 22.1 89.32 78.65 6.66
100.01 22.78 -9.345

void test(){
	cout << "-----------test----------- " << endl;
	ifstream in("sstream_fstream1.txt");
	string line;
	while (getline(in, line)){//获取文件的一行字符串到line中
		stringstream ss(line);//初始化 法1
		double x;
		while (ss >> x){//每一行包含不同个数的数字
			cout << x << "\t";
		}
		cout << endl;
	}
}

3、分割多行文件中每行用","隔开的字符串,每行包含的小数数字个数不同
sstream_fstream2.txt文件:
12.34,-3.21,90.34
23,22.1,89.32,78.65,6.66
100.01,22.78,-9.345,5.09

void test5(){
	cout << "-----------test5----------- " << endl;
	ifstream in("sstream_fstream2.txt");
	string line;
	vector<vector<double>> vv;
	while (getline(in, line)){
		stringstream ss(line);
		string tmp;
		vector<double> v;
		while (getline(ss, tmp, ',')){//按“,”隔开字符串
			v.push_back(stod(tmp));//stod: string->double
		}
		vv.push_back(v);
	}
	for (auto row : vv){
		for (auto col : row){
			cout << col << "\t";
		}
		cout << endl;
	}
	cout << endl;
}

4、读取 每一行按“姓名(空格)国籍(空格)分数(空格)一串话(里面包含空格)”格式存储的文件
sstream_fstream3.txt文件:
Leo France 95.5 I believe i can!
Aric Austria 88 Oh my god~~~
Athene China 100 Ha ha 不使用双截棍,哼哼哈嘿!!~~~#¥%……&

void test6(){
	cout << "-----------test6----------- " << endl;
	ifstream in("sstream_fstream3.txt");
	string line;
	while (getline(in, line)){
		stringstream ss(line);
		string tmp;
		int i = 0;
		string name, country;
		double score;
		string words;
		while (getline(ss, tmp,' ')){
			if (i == 0)name = tmp;
			else if (i == 1)country = tmp;
			else if (i == 2)score = stod(tmp);
			else words = words + tmp + " ";//将该行剩余的字符仍然按空格分割后依次追加在string words后面
			i++;
		}
		cout << name << "\t" << country << "\t\t" << score << "\t\t" << words << endl;
	}
}

三、结果:
C++ ifstream、sstream按行读取txt文件中的内容,并按特定字符分割,不用strtok