2016-03-03 76 views
-2

我正在尝试读取文件并将数据存储在结构数组中。 这是csv(逗号分隔值)格式,带有4个浮点值和一个字符串。使用ifstream从文件读取时编译时出错

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; 
} 
+1

你为什么不能理解你的编译器的错误信息?这很清楚! –

+0

你打算如何在每个'data'的* five *字符串中分割三个浮点数+一个字符串? – dasblinkenlight

+1

[如何使用逗号分隔值读写文本文件/从文本文件中读取/写入](http://stackoverflow.com/questions/1474790/how-to-read-write-into-from-text-file-with -逗号分隔值) – Rndp13

回答

1

用于输入的>>左操作数应该是一个输入流。但在

value >> da[i]; 

这是一个std::string。也许你想要一些istringstream,或者你的意思是input >> da[i];