-2

I am trying to read a file and store the data in a array of structures. The is in csv(Comma seperated values) format with 4 float values and a string.

1.2,2.3,3.4,abc
2.3,3.4,4.5,xyz

I have written following piece of code for the same, but however i am getting a compilation error

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>&}’

My code is as follows.

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;
}
Rndp13
  • 1,094
  • 1
  • 21
  • 35

1 Answers1

2

The left operand of >> used for input should be an input stream. But in

 value >> da[i];

it is a std::string. Perhaps you want some istringstream, or perhaps you mean input >> da[i];

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547