簡體   English   中英

如何在C++中將excel數據加載到數組中

[英]How to load excel data into an array in C++

作為家庭作業的一部分,我被要求從 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;
}

祝你好運 !

作為作業的一部分,我被要求從 excel 文件加載數據

有誰知道這是怎么做到的嗎?

我在網上找不到任何類似的東西..

(Excel 文件格式如下:

name1; ID1 
name2; ID2
name3; ID3

)

暫無
暫無

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

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