2016-07-24 197 views
0

嘗試對從文件讀取的C++中的字符串進行標記,用逗號分隔,但我只需要每行的前3個數據。C++ Tokenize字符串的一部分

例如: 的線條看起來像這樣:
140,152,2240,1,0,3:0:0:0:
156,72,2691,1,0,1:0:0: 0:
356,72,3593,1,0,1:0:0:0:

但我只需要這些行的前3個數據。在這種情況下:
156,72,2691
356,72,3593

我想這些數據添加到載體中我只是不知道如何跳過讀取一行該文件在前3個數據之後。

這是我當前的代碼:(canPrint默認爲true)

ifstream ifs; 
     ifs.open("E:\\sample.txt"); 
     if (!ifs) 
      cout << "Error reading file\n"; 
     else 
      cout << "File loaded\n"; 



     int numlines = 0; 
     int counter = 0; 
     string tmp; 

     while (getline(ifs, tmp)) 
     { 
      //getline(ifs, tmp); // Saves the line in tmp. 
      if (canPrint) 
      { 
       //getline(ifs, tmp); 
       numlines++; 

       // cout << tmp << endl; // Prints our tmp. 
       vector<string> strings; 
       vector<customdata> datalist; 
       istringstream f(tmp); 
       string s; 
       while (getline(f, s, ',')) { 
        cout << s << " "; 
        strings.push_back(s); 
       } 
       cout << "\n"; 


      } 

回答

1

如何檢查矢量大小頭?也許類似

while (strings.size() < 3 && getline(f, s, ',')) { ... }