c++ - 读取 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;
}
解决方案
解决了 :
#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;
}
推荐阅读
- bash - 如何在同一命令中同时使用变量和更改的变量
- python - 将数据从 JSON 文件转储到类变量并从类外部访问数据
- json - 如何获取 perl json 访问哈希参考
- php - 我可以使用 JQ fetch url 将数据传递给预定义的 PHP 类吗?
- c - 从字符串问题分配变量
- javascript - 如何仅在 JavaScript 中使用 URLs Tabs 数组将 HTML 页面呈现为 PNG/JPEG 图像?
- c++ - 可以同时保存 Foo* 和 std::shared_ptr 的类型
- ios - 更改 Google AdMob Native Ad Swift 的背景颜色
- java - 开始倒计时时不更新按钮标题
- wordpress - 如何在WordPress帖子中的图像下方添加社交分享按钮