【问题标题】:C++ reading csv into vector, getline() problemC++ 将 csv 读入向量,getline() 问题
【发布时间】:2019-07-05 03:01:47
【问题描述】:

我的 csv 文件数据是这样的:

Palmer Shannon,1.66805E+12,7500,3020
Jonas Kelley,1.62912E+12,9068,1496
Jacob Doyle,1.61608E+12,1112,3502
Iola Hayden,1.60603E+12,6826,4194

这是我的头文件:

#ifndef client_h
#define client_h
#include <string>

const int MAX_CLIENT = 20;

struct client {
    std::string name;
    long long  accountNum;
    int pwd;
    double balance;
};

第一个数据,String name 参考Palmer Shannon,long long 参考1.66805E+12,int pwd 参考7500 和双重平衡参考3020

这是我的 main.cpp 文件,我尝试创建一个向量来保存 csv 文件数据。

string str;
    std::vector<client> readClientProfile;
    while (getline(data, str))
        {

        client Client;
        istringstream iss(str);
        string token;
        getline(iss, Client.name, ',');

        getline(iss, token, ',');
        Client.accountNum = std::stoi(token);


        getline(iss, token, ',');
        Client.pwd = std::stoi(token);

        getline(iss, token, ',');
        Client.balance = std::stoi(token);


        readClientProfile.push_back(Client);
    }
    for (size_t i = 0; i < readClientProfile.size() - 1; i++)
    {

            std::cout << readClientProfile[i].name << "  "<<endl;
            std::cout << readClientProfile[i].accountNum << "  "<<endl;
            std::cout << readClientProfile[i].pwd << "  "<<endl;
            std::cout << readClientProfile[i].balance << "  "<<endl;

        }

问题是当我运行程序时,accountNum 只是显示第一个世界1。我无法更改 accountNum 的类型,因为这是分配请求。如何使用变量、字符和符号读取 long long 类型?

【问题讨论】:

    标签: c++ csv vector getline long-long


    【解决方案1】:

    您文件中的帐号存储为1.66805E+12。这是一个浮点数,而不是整数。当您使用 stoi 将其转换为时,它会解析字符串并在 . 处停止,因为这不是整数中的有效符号。这意味着stoi 将为所有帐号返回1。您可以通过首先使用stod1.66805E+12 转换为double 来解决此问题,然后您可以将double 存储为整数,如

    getline(iss, token, ',');
    Client.accountNum = std::stod(token);
    

    【讨论】:

      猜你喜欢
      • 2013-05-12
      • 2013-03-31
      • 2021-09-18
      • 2016-07-29
      • 2019-11-21
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 2017-08-02
      相关资源
      最近更新 更多