使用ifstream读取文件,使用stringstream根据空白切割字符串。
例子一
char str_name[30];
sprintf(str_name, "%06d.txt", IndFrame);
string str_name2(str_name);
string file_path = "/home/ychen/ORB_SLAM2/dataset/kitti_vo/" + str_name2;
cout << file_path << endl;
ifstream fin(file_path);
stringstream ss;
while(!fin.eof()) {
char line_1[256];
fin.getline(line_1,sizeof(line_1));
string line_2 = line_1;
if(line_2 == "") continue;
float f;
ss << line_2;
while(ss >> f) {
cout << f << " ";
}
ss.str("");
}
fin.close();
例子二
ifstream fin("/Users/test.txt");
if(fin.is_open()){
vector<vector<string>> dataset_all; // all dataset
vector<string> vocabulary; // vocabulary set
vector<vector<int>> onehot; // onehot set
vector<vector<double>> TF; // TF set
vector<double> IDF; // IDF set
vector<vector<double>> TFIDF; // TF_IDF set
vector<vector<int>> A; // A set is first half of the smatrox
vector<vector<int>> B; // B set is second half of the smatrix
int td=0, md=0, nd=0;
while(!fin.eof()){
char line_1[256];
fin.getline(line_1,sizeof(line_1));
string line_2 = line_1;
if(line_2=="") break; // to delete the null string
string line_3;
int count_t=0;
int count_s=(int)line_2.length()-1;
// after two tap is the string that we need
for (int i=0; i<line_2.length(); i++) {
if(line_2[i]=='\t'){
count_t++;
// to get the string that we need
if(count_t==2){
count_s=i;
break;
}
}
}
line_3 = line_2.substr(count_s+1,(line_2.length()-count_s));
vector<string> dataset_line; // the dataset in the every line
stringstream str(line_3);
string word;
while (str >> word) {
dataset_line.push_back(word);
// to get the vocabulary set
if(find(vocabulary.begin(),vocabulary.end(),word) == vocabulary.end()){
vocabulary.push_back(word);
}
}
dataset_all.push_back(dataset_line);
md = (int)dataset_all.size();
nd = (int)vocabulary.size();
}
fin.close();