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

基于C++实现带双引号转义的CSV文件关键词检索与指定列展示

Got it, let's build a C++ solution that handles your CSV search requirement properly—since CSV can have tricky edge cases like commas inside quoted fields, we need a robust parser first. Here's a complete implementation that does exactly what you need:

C++ CSV Search Tool

This code will prompt for a keyword, parse a CSV file (handling escaped commas and quotes), find entries with matching content, and display only the columns you specify.

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
#include <cctype>

// Helper to convert string to lowercase for case-insensitive matching
std::string to_lower(const std::string& s) {
    std::string res;
    for (char c : s) {
        res += std::tolower(static_cast<unsigned char>(c));
    }
    return res;
}

// Parse a single CSV line into fields, handling quoted values and escaped quotes
std::vector<std::string> parse_csv_line(const std::string& line) {
    std::vector<std::string> fields;
    std::string current_field;
    bool in_quote = false;

    for (size_t i = 0; i < line.size(); ++i) {
        char c = line[i];
        if (c == '"') {
            // Handle escaped quotes ("" becomes a single ")
            if (i + 1 < line.size() && line[i+1] == '"') {
                current_field += '"';
                ++i; // Skip the second quote
            } else {
                in_quote = !in_quote; // Toggle quote state
            }
        } else if (c == ',' && !in_quote) {
            // End of current field (only if not inside quotes)
            fields.push_back(current_field);
            current_field.clear();
        } else {
            current_field += c;
        }
    }
    // Add the final field in the line
    fields.push_back(current_field);
    return fields;
}

int main() {
    // Get search keyword from user
    std::string keyword;
    std::cout << "Enter search keyword: ";
    std::getline(std::cin, keyword);
    std::string keyword_lower = to_lower(keyword);

    // Configuration: Adjust these values to match your needs
    const std::string csv_file_path = "data.csv";
    const std::vector<int> columns_to_display = {0, 2, 4}; // 0-indexed column numbers

    // Open CSV file
    std::ifstream csv_file(csv_file_path);
    if (!csv_file.is_open()) {
        std::cerr << "Error: Could not open file " << csv_file_path << std::endl;
        return 1;
    }

    std::string line;
    // Read and print header (optional but helpful for context)
    if (std::getline(csv_file, line)) {
        std::vector<std::string> headers = parse_csv_line(line);
        std::cout << "\nMatching entries (columns: ";
        for (size_t i = 0; i < columns_to_display.size(); ++i) {
            int col = columns_to_display[i];
            if (col >= 0 && col < static_cast<int>(headers.size())) {
                std::cout << headers[col];
            } else {
                std::cout << "Column " << col;
            }
            if (i != columns_to_display.size() - 1) std::cout << ", ";
        }
        std::cout << "):\n";
    }

    // Process each data line
    while (std::getline(csv_file, line)) {
        if (line.empty()) continue; // Skip empty lines

        std::vector<std::string> fields = parse_csv_line(line);
        bool is_match = false;

        // Check if any field contains the keyword (case-insensitive substring match)
        for (const std::string& field : fields) {
            if (to_lower(field).find(keyword_lower) != std::string::npos) {
                is_match = true;
                break;
            }
        }

        if (is_match) {
            // Print only the specified columns
            for (size_t i = 0; i < columns_to_display.size(); ++i) {
                int col = columns_to_display[i];
                if (col >= 0 && col < static_cast<int>(fields.size())) {
                    std::cout << "\"" << fields[col] << "\"";
                } else {
                    std::cout << "(empty)";
                }
                if (i != columns_to_display.size() - 1) std::cout << ", ";
            }
            std::cout << "\n";
        }
    }

    csv_file.close();
    return 0;
}

Key Features & Customization Tips

  • Robust CSV Parsing: Handles commas inside quoted fields (e.g., "Doe, John") and escaped double quotes (e.g., "He said ""Hello""" becomes He said "Hello").
  • Case-Insensitive Search: The to_lower function ensures matches work regardless of capitalization. Remove the to_lower calls if you want case-sensitive matching.
  • Configurable Columns: Modify the columns_to_display vector to specify which columns to show (use 0-indexed numbers).
  • Header Support: Reads the first line as a header to display meaningful column names in results.

Example Usage

Suppose your data.csv looks like this:

"Name","Age","City","Email","Occupation"
"Younes Thabet",30,"Paris","younes@example.com","Engineer"
"Alice Smith",25,"London","alice@example.com","Designer"
"Younes Khan",35,"Berlin","younes.k@example.com","Teacher"
"Bob Jones",40,"New York","bob@example.com","Manager"

When you run the program and enter Younes, the output will be:

Matching entries (columns: Name, City, Occupation):
"Younes Thabet", "Paris", "Engineer"
"Younes Khan", "Berlin", "Teacher"

Compilation

Compile with a C++11 or later compiler:

g++ -std=c++11 csv_search.cpp -o csv_search

内容的提问来源于stack exchange,提问作者Younes Thabet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:00:36