簡體   English   中英

用C++讀取CSV文件中的兩列

[英]Reading two columns in CSV file in c++

我有一個兩列形式的 CSV 文件:姓名、年齡

為了閱讀和存儲信息,我這樣做了

struct person
{
    string name;
    int age;
}
person record[10];
ifstream read("....file.csv");

然而,當我做

read >> record[0].name;
read.get();
read >> record[0].age;

read>>name 給了我整行,而不僅僅是名字。 我怎樣才能避免這個問題,以便我可以將整數讀入年齡?

謝謝!

你可以先用std:getline讀取整行,然后通過std::istringstream解析它(必須是#include <sstream> ),就像

std::string line;
while (std::getline(read, line)) // read whole line into line
{
    std::istringstream iss(line); // string stream
    std::getline(iss, record[0].name, ','); // read first part up to comma, ignore the comma
    iss >> record[0].age; // read the second part
}

下面是一個完整工作的一般示例, 它將Ideone上的CSV文件標記為Live

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

int main()
{
    // in your case you'll have a file
    // std::ifstream ifile("input.txt");
    std::stringstream ifile("User1, 21, 70\nUser2, 25,68"); 

    std::string line; // we read the full line here
    while (std::getline(ifile, line)) // read the current line
    {
        std::istringstream iss{line}; // construct a string stream from line

        // read the tokens from current line separated by comma
        std::vector<std::string> tokens; // here we store the tokens
        std::string token; // current token
        while (std::getline(iss, token, ','))
        {
            tokens.push_back(token); // add the token to the vector
        }

        // we can now process the tokens
        // first display them
        std::cout << "Tokenized line: ";
        for (const auto& elem : tokens)
            std::cout << "[" << elem << "]";
        std::cout << std::endl;

        // map the tokens into our variables, this applies to your scenario
        std::string name = tokens[0]; // first is a string, no need for further processing
        int age = std::stoi(tokens[1]); // second is an int, convert it
        int height = std::stoi(tokens[2]); // same for third
        std::cout << "Processed tokens: " << std::endl;
        std::cout << "\t Name: " << name << std::endl;
        std::cout << "\t Age: " << age << std::endl;
        std::cout << "\t Height: " << height << std::endl;
    }
}

read>>name給了我整行而不僅僅是名字。 我怎么可能避免這個問題,以便我可以讀取整數到年齡?

read >> name會將所有內容讀入name直到遇到空格。

如果你有一個逗號分隔的行沒有空格,那么將整行讀入name是有意義的。

您可以使用std::getline將整行讀取到一個字符串。 然后使用各種標記std::string

示例標記std::string SO帖子:

如何在C ++中對字符串進行標記?
c ++ tokenize std string
使用標記拆分C ++ std :: string,例如“;”

你也許可以使用stringstreams,但我不相信,如果我是誠實的。 如果我是你,我會編寫一個小函數,將整行讀入一個字符串,之后,它應該搜索字符串中的分隔符。 前面的一切都是第一列,第二列后面的一切。 使用C ++提供的字符串操作,您可以在變量中移動這些部分(如果需要,可以將它們轉換為正確的類型)。 我寫了一個用於CSV解析的小型C ++庫,也許看看它可以幫助你。 你可以在GitHub上找到它。

編輯:在這個要點中你可以找到解析功能

非常感謝@vsoftco。 你已經解決了我長期以來的非生產性搜索問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM