c++ - Trouble reading file using getline (noob) -


i'm noob c++ student. i'm having trouble reading file array structure. class assignment not need 1 code me, want know i'm doing wrong. text file i'm reading formatted such:

giant armadillo#443#m hawaiian monk seal#711#m  iberian lynx#134#m javan rhinoceros#134#m etc... 

using getline() works correctly reading string '#' delimiter, not work int or char. how read int or char while checking delimiters? thanks, sorry if isn't written clearly, or formatted properly. i'm brand new so.

#include <iostream> #include<string> #include <fstream> #include <cstdlib> using namespace std;  //create new structure struct endangered {        string name;     int population;      char species; };   int main () {  endangered animals[200];  //initialize animals (int i=0; i<50; i++) {     animals[i].name=" ";     animals[i].population=0;     animals[i].species=' '; }  ifstream myfile; myfile.open("animals.txt"); int i=0; if (myfile.is_open()) {        while (myfile.eof())     {            //read string until delimiter #         getline(myfile, animals[i].name, '#');          //read int until delimiter #         getline(myfile, animals[i].population, '#');          //read char until delimiter         getline(myfile, animals[i].species, '/n');         i++;     }       return 0; } 

i'm sure cannot read data file this:

//read int until delimiter # getline(myfile, animals[i].population, '#'); 

because got sting , want assign int or char field.

look @ declaration:

istream& getline (istream& is, string& str, char delim); 

you have have string second argument. cannot pass function int or char , animals[i].population typeof int.

you should first load data string or char* buffer , use correct functions convert type want. functions atoi example.

to sum up. read data temporary buffer , convert it.

if doesn't i'll correct code didn't want :)


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -