在C 中读取CSV文件中的两个列

Reading two columns in CSV file in c++

本文关键字:两个 读取 CSV 文件      更新时间:2023-10-16

我的CSV文件的形式为两列:名称,年龄

要阅读和存储信息,我做了

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

但是,当我做

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

阅读>>名称给了我整个行,而不仅仅是名字。我怎么可能避免这个问题,以便可以将整数读成年龄?

谢谢!

您可以首先使用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文件

#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, 70nUser2, 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的帖子:

如何将C 中的字符串表示为?
C 令牌std String
使用令牌分配C STD ::字符串,例如&quot;&quot

您可能可以使用弦乐,但是如果我说实话,我不会相信这一点。如果我是您,我会写一个小函数,将整个行读为字符串,之后,它应该在字符串中搜索隔板字符。前面的所有内容都是第一列,第二列是第二列背后的所有内容。借助C 提供的字符串操作,您可以将这些零件移动到变量中(如果需要,可以将它们转换为正确的类型)。我为CSV解析写了一个小型C 库,也许可以看一下它可以帮助您。您可以在github上找到它。

编辑:在这个要旨中,您可以找到解析功能