首页 > 解决方案 > 读取 csv 文件的特定行并添加到数组中

问题描述

我想选择 csv 文件的特定行并将其值添加到数组中。

例如,如果我选择“二”,则 xyz 数组将为 {0,1,2,3,4,5,6,7}

有人可以帮助我吗?

测试.txt:

one,1,2,3,4,5,6,7,8
two,0,1,2,3,4,5,6,7
three,8,7,6,5,4,3,2,1

我的程序的简化版本:

#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

int main()
{
    int xyz [8];
    char name[10];
    vector<string> word;
    int i = 0;

    printf("Name ?");
    scanf("%s", &name); // Input : two

    ifstream fichier("test.txt", ios::in);

    if(fichier)
    {
        string ligne;
        while(getline(fichier, ligne))
        {
            istringstream ss(ligne);
            std::string token;
            getline(ss,token,',');
            //cout << token << endl;
            if (token == name) {
                //printf("Correct name\n");
                while(getline(ss,ligne,',')){
                    cout << i;
                    cout << "-->";
                    cout << ligne << endl;
                    //How to : xyz[i] = ligne; ? 
                    i++;
                }
            }
        }
    }
    //printf("%d\n", xyz[0]); // Output : 0
    //printf("%d\n", xyz[7]); // Output : 7
    return 0;
}

标签: c++

解决方案


解决了 :

#include <windows.h>
#include <stdio.h>
#include <fstream>
#include <sstream>

using namespace std;

int main()
{
    int xyz [8];
    char name[50];
    int i = 0;
    //int n;
    printf("Name ?");
    scanf("%s", &name); // Input : two

    ifstream fichier("test.txt", ios::in);
    if(fichier)
    {
        string ligne;
        while(getline(fichier, ligne))
        {
            istringstream ss(ligne);
            std::string token;
            getline(ss,token,',');
            if (token == name) {
                while(getline(ss,ligne,','))
                {
                    //std::istringstream(ligne) >> n;
                    //xyz[i] = n;
                    xyz[i] = std::stoi(ligne);
                    i++;
                }
            }
        }
        fichier.close();
    }
    printf("%d\n", xyz[0]); // Output : 0
    printf("%d\n", xyz[7]); // Output : 7
    return 0;
}

推荐阅读