2014-11-23 55 views
0
readInputRecord(ifstream &inputFile, 
string &taxID, string &firstName, string &lastName, string &phoneNumber) {  
    while (!inputFile.eof()) { 
     inputFile >> firstName >> lastName >> phoneNumber >> taxID;  
    } 
} 

正如你所看到的,我讀取的數據就像是一個標準的讀取輸入文件。麻煩的是數據字段可以是空白的,例如「,」,並且不包括括號之間的數據。我一直在這裏和其他地方閱讀論壇,一種常見的方法似乎是使用getline(東西,東西,','),但是這樣會讀取停在逗號處的數據。包含逗號的方法是什麼,因爲輸出文件應該讀取並輸出變量「,,」(如果讀取的話)。如果我想從包含逗號的輸入文件(如1,2,3)中讀取逗號描述的數據?

+0

一個有效的解決方案是在組織起來的數據? – Oncaphillis 2014-11-23 23:38:06

+0

是的。輸入示例:john,doe,123-456-7890,123-45-6789 – 2014-11-24 00:35:04

+0

http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – 2014-11-24 01:45:41

回答

0

如果你有升壓開發安裝,則包括頭文件<boost/algorithm/string.hpp>

void readInputRecord(std::ifstream &inputFile, std::vector<std::string>& fields) { 
    std::string line; 
    fields.clear(); 
    while (std::getline(inputFile, line)) { 
      boost::split(fields, line, boost::is_any_of(",")); 
      for (std::vector<std::string>::iterator it = fields.begin(); it != fields.end(); ++it) 
       std::cout << *it << "#"; 

      std::cout << std::endl; 
    } 
} 

的所有字段包含在載體中,包括空場。該代碼未經測試,但應該可以工作。

0

你並不需要顯式閱讀「」以確保出現了「」和std::getline(...)提供結合std::stringstream

// Read the file line by line using the 
// std line terminator '\n'  

while(std::getline(fi,line)) { 
    std::stringstream ss(line);      
    std::string cell;        

    // Read cells withing the line by line using 
    // ',' as "line terminator"   
    while(std::getline(fi,cell,',')) { 
     // here you have a string that may be '' when you got 
     // a ',,' sequence 
     std::cerr << "[" << cell << "]" << std::endl; 
    } 
}