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;
	}
}

三、結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章