You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CSV数据提取后两行合并至同一单元格问题求助

Hey, let's figure out what's going wrong here and fix it step by step!

The Root Causes of Your Issue

From your description and code, there are a few key issues leading to the merged cells in your output CSV:

  • Wrong delimiter for parsing: Your input CSV uses semicolons (;) as separators, but your code is splitting lines using commas (,) with getline(lineStream,cell,','). This means each entire line is being treated as a single cell, which throws off the column structure entirely.
  • Unescaped commas in output: You're replacing dots (.) with commas in cell content, but CSV rules require that any cell containing commas (or quotes/newlines) be wrapped in double quotes. Without this, tools like Excel will interpret those commas as column separators, leading to messed-up rows and merged cells.
  • Inefficient column filtering: Your inner for loop runs 5 times for every cell—this isn't the direct cause of the merge issue, but it's unnecessary and can be optimized.

Fixed Code

Here's the revised code that addresses all these problems, plus a bonus implementation of your missing row-filtering logic:

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <algorithm>
#include <unordered_set>
using namespace std;

int main(){
    // Names of entries to keep (for row filtering)
    unordered_set<string> rows2keep = {"Name1","Name2"};
    // Column indices to keep (1-based matching your input structure)
    unordered_set<int> cols2keep = {1,2,3,4,5};
    
    ifstream data("Nameoffile.csv");
    if (!data.is_open()) {
        cerr << "Oops! Failed to open the input file." << endl;
        return 1;
    }
    
    ofstream outdata("sorting.csv");
    if (!outdata.is_open()) {
        cerr << "Oops! Failed to create the output file." << endl;
        data.close();
        return 1;
    }
    
    string line;
    int row_num = 0;
    
    while(getline(data, line)){
        row_num++;
        stringstream lineStream(line);
        string cell;
        int col_num = 0;
        bool first_cell = true;
        string current_name;

        // First, grab the Name value for row filtering (assuming Name is column 2)
        string temp_line = line;
        stringstream temp_stream(temp_line);
        int temp_col = 0;
        while(getline(temp_stream, cell, ';') && temp_col < 2){
            temp_col++;
            if (temp_col == 2) current_name = cell;
        }

        // Skip non-header rows that don't match our target names
        if (row_num > 1 && rows2keep.find(current_name) == rows2keep.end()) {
            continue;
        }

        // Process each cell in the row
        stringstream lineStreamProcess(line);
        while(getline(lineStreamProcess, cell, ';')){ // Use semicolon to split input cells
            col_num++;
            if (cols2keep.count(col_num)){
                // Replace dots with commas as required
                replace(cell.begin(), cell.end(), '.', ',');
                
                // Wrap cell in quotes if it contains commas/quotes/newlines (CSV standard)
                if (cell.find(',') != string::npos || cell.find('"') != string::npos || cell.find('\n') != string::npos) {
                    // Escape existing quotes by doubling them
                    size_t pos = 0;
                    while ((pos = cell.find('"', pos)) != string::npos) {
                        cell.replace(pos, 1, "\"\"");
                        pos += 2;
                    }
                    cell = "\"" + cell + "\"";
                }
                
                // Add separator before cell (avoid extra semicolon at row start)
                if (!first_cell) {
                    outdata << ";";
                    cout << ";";
                } else {
                    first_cell = false;
                }
                
                outdata << cell;
                cout << cell;
            }
        }
        // Add newline after each valid row
        outdata << "\n";
        cout << "\n";
    }
    
    data.close();
    outdata.close();
    return 0;
}

Key Fixes Explained

  1. Correct input delimiter: Changed getline(lineStream, cell, ',') to getline(lineStream, cell, ';') to match your input CSV's semicolon separators. This ensures each cell is parsed correctly.
  2. Proper CSV escaping: Added logic to wrap cells containing commas (or quotes/newlines) in double quotes, and escape any existing quotes by doubling them. This ensures tools like Excel read the CSV without mangling rows.
  3. Optimized filtering: Switched to unordered_set for columns/rows to keep—checking if a column/row should be preserved is now O(1) instead of looping through arrays every time.
  4. Added error checking: The code now verifies if files open successfully, so you'll get a clear message if something's wrong with file paths.
  5. Row filtering implemented: Added logic to skip rows that don't match your target names, while keeping the header row intact.

内容的提问来源于stack exchange,提问作者Vincent-Olivier Faullem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:14:39