2017-05-08 30 views
1

我有了很多行的文本文件,一個例子是如何我分隔字符串和各部分儲存在不同的載體

約翰:學生:業務

可能:講師:數學

鮑勃:學生:數學

我如何拆分起來,並將它們存儲在不同的載體如:

向量1:約翰,可以,鮑勃

vector2:學生,講師,學生

的Vector3:商務,數學,數學

我當前的代碼是:

ifstream readDetails(argv[1]); 
while (getline (readEvents, line, ':')){ 
    cout << line << endl; 
} 

只拆分字符串,但我想不出任何方法來分離字符串並將它們存儲到向量中。

回答

0

您可以創建矢量矢量並使用標記索引進行播放。

如果流有時可能具有較少的標記,則需要處理該情況。

#include <iostream> 
#include <string> 
#include <sstream> 
#include <vector> 
int main() { 

    const int NUM_TOKENS = 3; 
    std::vector<std::vector<std::string>> v(NUM_TOKENS); 
    int token = 0; 
    std::string str("Mary:Had:Lamb"); 
    std::istringstream split(str); 
    std::string line; 
    while (std::getline (split, line, ':')){ 
     v[token++].push_back(line); 
     if (token == NUM_TOKENS) 
      token = 0; 

    } 
    return 0; 
} 
0

這可以使用嵌套矢量(aka 2D矢量)和嵌套循環來完成。外部循環用於將輸入拆分成行,內部循環用於拆分由':'分隔的每行的標記。

#include <string> 
#include <sstream> 
#include <vector> 

int main() 
{ 
    std::istringstream in{ 
     "john:student:business\n" 
     "may:lecturer:math\n" 
     "bob:student:math" 
    }; 

    std::vector< std::vector<std::string> > v{ 3 }; // Number of tokens per line 

    std::string line; 
    // Loop over the lines 
    while(std::getline(in, line)) { 
     std::istringstream lineStrm{ line }; 
     // Loop to split the tokens of the current line 
     for(auto& col : v) { 
      std::string token; 
      std::getline(lineStrm, token, ':'); 
      col.push_back(token); 
     } 
    } 
} 

Live demo on Coliru.

0

創建字符串的載體,並相應地存儲數據。如果不使用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 
相關問題