2009-09-25 181 views
16

如何从文件中读取数据,如果我的文件是这样的用逗号分隔值用逗号分隔值

1, 2, 3, 4, 5\n 
6, 7, 8, 9, 10\n 
\n 

和读取文件后,我要如何读取写入/从文本文件将数据以上面相同的格式写回到其他文件中。

我可以得到线的总数量,使用

string line; 
while(!file.eof()){ 
     getline(file,line); 
     numlines++; 
    } 
    numline--; // remove the last empty line 

,但我怎么能知道行/线总的数字位数?

我也有整数矢量来存储数据。 因此,我想读取第一行,然后计算该行中的元素总数,这里是5(1,2,3,4,5),并将它们存储在数组/矢量中,然后读取下一行并将它们存储在再次导航,直到我到达EOF。

然后,我想将数据写入到文件,再次,我想这会做将数据写入到文件的工作,

numOfCols=1; 
for(int i = 0; i < vector.size(); i++) 
{ 
    file << vector.at(i); 
    if((numOfCols<5) file << ",";//print comma (,) 
    if((i+1)%5==0) 
    { 
        file << endl;//print newline after 5th value 
        numOfCols=1;//start from column 1 again, for the next line 
    } 
    numOfCols++; 
} 
file << endl;// last new line 

所以,我的主要问题是如何从文件中读取数据用逗号分隔值

感谢

回答

24

第1步: 不要这样做:直到你尝试阅读过去,

while(!file.eof()) 
{ 
    getline(file,line); 
    numlines++; 
} 
numline--; 

的EOF是不正确的。 标准模式是:

while(getline(file,line)) 
{ 
    ++numline; 
} 

还要注意的是的std ::函数getline()可任选地采取的第三参数。这是要打破的角色。默认情况下,这是行终止符,但您可以指定一个逗号。

while(getline(file,line)) 
{ 
    std::stringstream linestream(line); 
    std::string   value; 

    while(getline(linestream,value,',')) 
    { 
     std::cout << "Value(" << value << ")\n"; 
    } 
    std::cout << "Line Finished" << std::endl; 

} 

如果将所有值存储在单个向量中,则使用固定宽度将其打印出来。然后我会做这样的事情。

struct LineWriter 
{ 
     LineWriter(std::ostream& str,int size) 
       :m_str(str) 
       ,m_size(size) 
       ,m_current(0) 
     {} 

     // The std::copy() does assignement to an iterator. 
     // This looks like this (*result) = <value>; 
     // So overide the operator * and the operator = to 
     LineWriter& operator*() {return *this;} 
     void operator=(int val) 
     { 
       ++m_current; 
       m_str << val << (((m_current % m_size) == 0)?"\n":","); 
     } 

     // std::copy() increments the iterator. But this is not usfull here 
     // so just implement too empty methods to handle the increment. 
     void operator++()  {} 
     void operator++(int) {} 

     // Local data. 
     std::ostream&   m_str; 
     int const    m_size; 
     int      m_current; 
}; 

void printCommaSepFixedSizeLinesFromVector(std::vector const& data,int linesize) 
{ 
    std::copy(data.begin(),data.end(),LineWriter(std::cout,linesize)); 
} 
+0

这是干什么的? std :: stringstream linestream(line); – Curious 2009-09-25 00:38:15

+0

它创建一个字符串流对象。它的行为与std :: cin,std :: cout或std :: fstream文件流类似,但使用字符串作为数据源。所以实际上它只是一条线的流。 – 2009-09-25 00:44:51

+0

当我尝试编译时,出现这个错误,变量'std :: stringstream linestream'有初始值设定项但是不完整的类型。 我已经包含了所有需要的头文件。 – Curious 2009-09-25 01:11:03

0

尝试stringstream类:

#include <sstream> 

以防万一,查找Stroustrup的 “C++程序设计语言特别版” 页面641的例子。

它适用于我,我有一段时间试图找出这一个。

5

这里我发布的CSV读代码以及写代码。我检查了它的工作正常。

#include <iostream> 
#include <fstream> 
#include <sstream> 
#include <vector> 
using namespace std; 

void readCSV(istream &input, vector< vector<string> > &output) 
{ 
    string csvLine; 
    // read every line from the stream 
    while(getline(input, csvLine)) 
    { 
      istringstream csvStream(csvLine); 
      vector<string> csvColumn; 
      string csvElement; 
      // read every element from the line that is seperated by commas 
      // and put it into the vector or strings 
      while(getline(csvStream, csvElement, ',')) 
      { 
        csvColumn.push_back(csvElement); 
      } 
      output.push_back(csvColumn); 
    } 
} 

int main() 
{ 
    ofstream myfile; 
    string a; 
    fstream file("b.csv", ios::in); 
    myfile.open ("ab.csv"); 
    if(!file.is_open()) 
    { 
      cout << "File not found!\n"; 
      return 1; 
    } 
    // typedef to save typing for the following object 
    typedef vector< vector<string> > csvVector; 
    csvVector csvData; 

    readCSV(file, csvData); 
    // print out read data to prove reading worked 
    for(csvVector::iterator i = csvData.begin(); i != csvData.end(); ++i) 
    { 
      for(vector<string>::iterator j = i->begin(); j != i->end(); ++j) 
      { 
      a=*j; 
        cout << a << " "; 
      myfile <<a<<","; 

} 
myfile <<"\n"; 
cout << "\n"; 
} 
myfile.close(); 
system("pause"); 

}