在 C++ 中读取 csv 文件并存储在不同的变量中
read csv file in c++ and store in different variable
我需要读取一个类似于 CSV 文件的文件(第一行与其余文本不同)。
文件的结构是这样的,第一行和每行之后包含一个名字和一个名字:
first line
Barack Obama
Jacques Chirac
John Paul-Chouki
etc.
我需要使用 getline 存储姓名和名字不同的变量:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
//open file with ifstream (with full path)
ifstream file("file.txt");
string line;
string lineContent;
string firstname;
string name;
int i=1;
//check if file is really open
if ( ! file.is_open() ) {
cout <<" Failed to open" << endl;
}
else {
cout <<"Opened OK" << endl;
}
while(file >> line) {
if(i == 1)
cout << "1st line==> "+line << endl;
else
getline(file,line, ' ');
cout << "result==> "+line << endl;
i++;
}
}
目前还不行。
问题是file >> line
和getline(file,line, ' ')
都读取了文件。
不如试试:
...
while(getline(file,line)) {
if(i == 1)
cout << "1st line==> "+line << endl; // ignore first line
else { // read data
string firstname, lastname;
stringstream sst(line);
sst >> firstname >> lastname;
cout << "result==> "<< firstname<<" "<<lastname << endl;
// where to store the data ?
}
i++;
}
不清楚必须将数据存储在何处。因此,完成将名字和姓氏添加到数组或更好的向量中的代码。
编辑:
请注意,您的示例数据不是 CSV 格式:CSV 表示 Comma Separated Values。如果要用逗号分隔数据,您可以将 sst>>...
行替换为
getline(getline (sst, firstname, ','),lastname, ',');
我需要读取一个类似于 CSV 文件的文件(第一行与其余文本不同)。
文件的结构是这样的,第一行和每行之后包含一个名字和一个名字:
first line
Barack Obama
Jacques Chirac
John Paul-Chouki
etc.
我需要使用 getline 存储姓名和名字不同的变量:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
//open file with ifstream (with full path)
ifstream file("file.txt");
string line;
string lineContent;
string firstname;
string name;
int i=1;
//check if file is really open
if ( ! file.is_open() ) {
cout <<" Failed to open" << endl;
}
else {
cout <<"Opened OK" << endl;
}
while(file >> line) {
if(i == 1)
cout << "1st line==> "+line << endl;
else
getline(file,line, ' ');
cout << "result==> "+line << endl;
i++;
}
}
目前还不行。
问题是file >> line
和getline(file,line, ' ')
都读取了文件。
不如试试:
...
while(getline(file,line)) {
if(i == 1)
cout << "1st line==> "+line << endl; // ignore first line
else { // read data
string firstname, lastname;
stringstream sst(line);
sst >> firstname >> lastname;
cout << "result==> "<< firstname<<" "<<lastname << endl;
// where to store the data ?
}
i++;
}
不清楚必须将数据存储在何处。因此,完成将名字和姓氏添加到数组或更好的向量中的代码。
编辑:
请注意,您的示例数据不是 CSV 格式:CSV 表示 Comma Separated Values。如果要用逗号分隔数据,您可以将 sst>>...
行替换为
getline(getline (sst, firstname, ','),lastname, ',');