要求我作为作业的一部分从excel文件加载数据
有谁知道这是怎么做到的吗?
我在网上找不到任何东西。
(Excel文件的格式为:
name1; ID1
name2; ID2
name3; ID3
)
最佳答案
您似乎没有做任何努力。只要看一门有关“如何用C ++读取文件”的C ++课程,就会为您提供答案。
我无法相信您在网上找不到任何东西,除非您从未搜索过任何东西。
您将在下面看到一个示例,该示例如何读取具有指定格式(我想是.csv)的文件。但是它不能处理您的数据文件损坏的情况。而且...我不会解释代码,我想您必须努力自己在线搜索C ++课程或C ++文档,这些内容将向您解释我的说明。用来完全理解代码的作用。
#include <fstream>
#include <iostream>
#include <vector>
std::vector<std::string> split(const std::string & s, char c);
int main()
{
std::string file_path("data.csv"); // I assumed you have that kind of file
std::ifstream in_s(file_path);
std::vector <std::pair<std::string, std::string>> content;
if(in_s)
{
std::string line;
while(getline(in_s, line))
{
std::vector<std::string> splitted(split(line, ';'));
while(splitted[1][0] == ' ')
splitted[1].erase(0, 1); // remove the white(s) space(s)
content.push_back(std::make_pair(splitted[0], splitted[1]));
}
in_s.close();
}
else
std::cout << "Could not open: " + file_path << std::endl;
for(std::pair<std::string, std::string> line : content)
std::cout << line.first << "; " << line.second << std::endl;
return 0;
}
std::vector<std::string> split(const std::string & s, char c)
{
std::vector<std::string> splitted;
std::string word;
for(char ch : s)
{
if((ch == c) && (!word.empty()))
{
splitted.push_back(word);
word.clear();
}
else
word += ch;
}
if(!word.empty())
splitted.push_back(word);
return splitted;
}
祝好运 !