【问题标题】:If I wanted to read in comma delineated data from an input file such as 1, 2, 3 INCLUDING the commas?如果我想从输入文件(例如 1、2、3 包括逗号)中读取逗号分隔的数据?
【发布时间】:2014-11-23 22:13:58
【问题描述】:
readInputRecord(ifstream &inputFile, 
string &taxID, string &firstName, string &lastName, string &phoneNumber) {      
    while (!inputFile.eof()) {
        inputFile >> firstName >> lastName >> phoneNumber >> taxID;     
    }   
}

如您所见,我像读取标准读取输入文件一样读取数据。问题是数据字段可以为空白,例如“,”,并且括号之间不包含数据。我一直在这里和其他地方阅读论坛,一种常见的方法似乎是使用 getline(stuff, stuff, ','),但随后会读取在逗号处停止的数据。包含逗号的方法是什么,因为输出文件应该读取,然后为变量输出“,”(如果已读取)。

【问题讨论】:

标签: c++ file-io ifstream ofstream


【解决方案1】:

您无需显式读取“,”以确保存在“,”,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; 
    } 
} 

【讨论】:

    【解决方案2】:

    如果你安装了 boost-dev,则包含头文件&lt;boost/algorithm/string.hpp&gt;

    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;
        }
    }
    

    所有字段都包含在向量中,包括空字段。代码未经测试,但应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多