創建字符串的載體,並相應地存儲數據。如果不使用std::istringstream
,你基本上可以利用substr()
和find()
附帶String類,因此:
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream inFile("data.txt");
string line;
vector<string> vStr1,vStr2, vStr3;
while(std::getline(inFile, line)){
string::size_type idx1 = line.find(":");
string::size_type idx2 = line.rfind(":");
vStr1.push_back(line.substr(0,idx1));
vStr2.push_back(line.substr(idx1+1,idx2-idx1-1));
vStr3.push_back(line.substr(idx2+1));
}
cout << "vector1: ";
for(int i(0); i < vStr1.size(); ++i){
cout << vStr1[i] << " ";
}
cout << endl;
cout << "vector2: ";
for(int i(0); i < vStr2.size(); ++i){
cout << vStr2[i] << " ";
}
cout << endl;
cout << "vector3: ";
for(int i(0); i < vStr3.size(); ++i){
cout << vStr3[i] << " ";
}
cout << endl;
return 0;
}
結果是
vector1: john may bob
vector2: student lecturer student
vector3: business math math