2016-07-24 206 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, ',')) { ... }