我正在尝试读取文件并将数据存储在结构数组中。
它采用csv
(逗号分隔值)格式,包含4个浮点值和一个字符串。
1.2,2.3,3.4,abc
2.3,3.4,4.5,xyz
我已经编写了以下代码,但是我收到了编译错误
readfile.c++: In function ‘void read_data()’:
readfile.c++:38:7: error: no match for ‘operator>>’ (operand types are ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ and ‘data’)
value >> da[i];//sep_len << sep_wid << pet_len << pet_wid << type;
^
readfile.c++:16:10: note: candidate: std::istream& operator>>(std::istream&, data&)
istream& operator>>( istream& ins, data& dat )
^
readfile.c++:16:10: note: no known conversion for argument 1 from ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘std::istream& {aka std::basic_istream<char>&}’
我的代码如下。
include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
struct data
{
string sep_len;
string sep_wid;
string pet_len;
string pet_wid;
string type;
};
istream& operator>>( istream& ins, data& dat )
{
return (ins >> dat.sep_len
>> dat.sep_wid
>> dat.pet_len
>> dat.pet_wid
>> dat.type);
}
void read_data()
{
struct data da[150];
string line;
int i=0;
string name="iris.data";
ifstream input( name.c_str() );
while( (getline(input,line)))
{
stringstream iss(line);
string value;
while ( getline(iss,value,','))
{
value >> da[i];//sep_len << sep_wid << pet_len << pet_wid << type;
i++;
}
}
}
int main()
{
read_data();
return 0;
}
答案 0 :(得分:1)