[英]read .csv file and store into arrays using only <iostream> c++
Hello I am wondering what the most efficient way would be to read a .csv file and store each comma separated item into its own array or variable.您好,我想知道读取 .csv 文件并将每个逗号分隔的项目存储到其自己的数组或变量中的最有效方法是什么。 I can only use #include <iostream>
.我只能使用#include <iostream>
。 I was thinking about maybe using .getLine(), but all i would know is the delimeter and value to store since there is no <fstream>
allowed.我正在考虑使用 .getLine(),但我只知道要存储的分隔符和值,因为不允许使用<fstream>
。 That being said does anyone know how I could go about this?话虽如此,有人知道我该怎么做吗? Thanks in advance!提前致谢!
This is the layout of the file.这是文件的布局。 The first line indicates the umber of rows to be read.第一行表示要读取的行数。
input file输入文件
3
2014,Computer Science,Utah,1568,44.9
2014,Marketing,Michigan,23745,983
215,Business Management, Idaho,256,674
code:代码:
int year;
char* major = new char[40];//cant be longer than 40 characters
char* state = new char[40];
int enrolled;
int rate;
char p;//for cin.get characters possibly
cin>>rows
for(int i = 0; i <= rows; i++){
HMMMMM?
}
You can use cin.getline()
function which also accepts a delimiter.您可以使用cin.getline()
函数,该函数也接受分隔符。 As for storing the entire csv record, you can define a structure which stores all the fields.至于存储整个 csv 记录,您可以定义一个存储所有字段的结构。
#include <iostream>
#include <cstring>
using namespace std;
typedef struct temp_struct {
char major[40];
char state[40];
float rate;
int year;
int enrolled;
} RECORD;
int main() {
int rows;
cin >> rows;
RECORD r[rows];
char temp[100];
for(int i = 0; i < rows; i++) {
cin.getline(temp, 100, ',');
r[i].year = atoi(temp);
cin.getline(temp, 100, ',');
strcpy(r[i].major, temp);
cin.getline(temp, 100, ',');
strcpy(r[i].state,temp);
cin.getline(temp, 100, ',');
r[i].enrolled = atoi(temp);
cin.getline(temp, 100);
r[i].rate = atof(temp);
cout << r[i].year << " " << r[i].major << " " << r[i].state << " ";
cout << r[i].enrolled << " " << r[i].rate << endl;
}
return 0;
}
For delimiters, the first four delimiters would be ,
and since the last value rate
has no ,
following it rather there's a \\n
, no delimiter is specified in the cin.getline()
(since default delimiter is \\n
itself).对于分隔符,前四个分隔符将是,
并且由于最后一个值rate
没有,
后面有一个\\n
,在cin.getline()
没有指定分隔符(因为默认分隔符是\\n
本身)。
I have tested it;我已经测试过了; here's the link https://ideone.com/ycht1b这是链接https://ideone.com/ycht1b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.