我的 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 文件,我尝试创建一个 vector 来保存 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类型?
最佳答案
您文件中的帐号存储为 1.66805E+12
。这是一个 float ,不是整数。当您使用 stoi
将其转换为 an 时,它会解析字符串并在 .
处停止,因为它不是整数中的有效符号。这意味着 stoi
将为所有帐号返回 1
。您可以通过首先使用 stod
将 1.66805E+12
转换为 double
来解决此问题,然后您可以存储该 double
作为一个整数,如
getline(iss, token, ',');
Client.accountNum = std::stod(token);
关于C++将csv读入vector,getline()问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54633588/