2013-11-02 33 views
0

如何使用substr函數讀取第一列值(名稱,名稱2和名稱3)?閱讀,直到使用for循環的某個字符

name;adress;item;others; 
name2;adress;item;others; 
name3;adress;item;others; 

我已經寫了

cout << "Read data.." << endl; 
    if (dataFile.is_open()) { 
     i=-1; 
     while (dataFile.good()) { 
      getline (dataFile, line); 
      if (i>=0) patient[i] = line; 
      i++; 
     } 
     dataFile.close(); 
    } 

回答

0
#include <string> 
#include <iostream> 
#include <fstream> 
#include <vector> 

int main() 
{ 
    std::fstream f("file.txt"); 
    if(f) 
    { 
     std::string line; 
     std::vector<std::string> names; 
     while(std::getline(f, line)) 
     { 
      size_t pos = line.find(';'); 
      if(pos != std::string::npos) 
      { 
       names.push_back(line.substr(0, pos)); 
      } 
     } 

     for(size_t i = 0; i < names.size(); ++i) 
     { 
      std::cout << names[i] << "\n"; 
     } 
    } 

    return 0; 
} 
0

像這樣:

int pos = s.find(';'); 
if (pos == string::npos) ... // Do something here - ';' is not found 
string res = s.substr(0, pos); 

你需要找到第一​​3210的位置,然後採取substr從零到位置。這是一個demo on ideone

+0

閱讀每行第一個?爲什麼不趕上新的路線並選擇第一條;? –

+0

@BernardoBaalen那會比較慢。另外,'getline'刪除所有換行符。 – dasblinkenlight

0

第一個分號被讀取之前,您可以忽略該行的內容後,剩下的:

std::vector<std::string> patient; 

std::string line; 
while (std::getline(file, line, ';')) 
{ 
    patient.push_back(line); 
    file.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
}