为什么每两行最终都在同一个单元格中?

时间:2018-01-04 13:48:41

标签: c++ csv cell ofstream

我已经来这里多年了,我总是发现以前的问题或主题可以帮助我,但今天我似乎无法找到问题的答案,所以我写了第一个问题

我有一个带有以下布局的.csv文档。

CELL A1: Title1,Title2,Title3,... CELL A2: Date1,Name1,Data11,Data12,Data13,...
CELL A3: Date2,Name2,Data21,Data22,Data23,...

我需要提取一组特定的列以及具有特定名称的行(尚未包含在显示的代码中)。

问题是输出的文本行在第一个单元格中成对写入,而它们应该都有自己的行。我尝试写入.txt文件,没有发现任何问题。看起来像这样: 第1行:A:Title1 B:Title2 C:Title3 ...... 第2行:A:Date1,Name1,Data11,Data12,Data13,Date2 B:Name2 C:Data21 D:Data22 ......

我的csv使用分号(&#34 ;;")作为分隔符。

这是到目前为止的代码(我试图重新编写无用的内容):

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;

int main(){
//Name of the rooms to be extracted
char *row2keep[] = {"Name1","Name2"};
//Number of the rows to be extracted
int col2keep[] = {1,2,3,4,5};
ifstream  data("Nameoffile.csv");

string  line;
string  cell;
int     col = 0;
int     row = 0;
ofstream outdata;
outdata.open("sorting.csv", ios::app);

while(getline(data,line)){
    col = 0;
    row ++;
    stringstream  lineStream(line);
    while(getline(lineStream,cell,',')){
        col ++;
        for(int c = 0; c < 5; ++c){
            if(col2keep[c] == col){
                replace(cell.begin(),cell.end(),'.',',');
                cout << cell << ";";
                outdata << cell << ";";
            }
        }
    }
    cout << "\n";
    outdata << "\n";
}
data.close();
outdata.close();
return 0;
}

问题似乎是最终while()循环中的for()循环以某种方式与ofstream混淆,因为当我删除它时,所有八行在不同行中一个接一个地结束而没有问题。

0 个答案:

没有答案