0

I'm trying to correctly parse the file object RecordFile using commas instead of spaces and then assign the data to the correct variables. I am currently parsing using spaces as seen in the record sample below. Any suggestions?

    ifstream RecordFile("records.txt"); 

    while (!RecordFile.eof())    
    {
        string f, l, aba, id, e;                          
        RecordFile >> f >> l >> aba >> id >> e;           
        Recordsarray[i].setRecords(f, l, aba, id, e);     

       i++;
       recordcounter++; 
    }

    RecordFile.close();            

    return recordcounter;          

Example Record:

Albert Green 000000000 8181234567 a.green@piercecollege.edu
dacimovic
  • 1
  • 1
  • not quite clear. There are no commas in your example record – 463035818_is_not_an_ai May 25 '20 at 10:30
  • [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Yksisarvinen May 25 '20 at 10:31
  • what exactly is wrong with your code? Please include a [mcve] together with input, output and expected output – 463035818_is_not_an_ai May 25 '20 at 10:33
  • @Yksisarvinen The code works, it's just doesn't work if I would replace the spaces in the record with commas – dacimovic May 25 '20 at 10:39
  • @idclev463035818 My code is working, it's just parsing using spaces instead of commas, as seen in this line: RecordFile >> f >> l >> aba >> id >> e; My goal is to read CVS files instead of a regular text file, so imagine the spaces in the record replaced with commas. – dacimovic May 25 '20 at 10:41
  • please don't let us guess or imagine what your problem is. If your real input has commas then please add that instead of input that has no commas. Anyhow, this should answer your question: https://stackoverflow.com/questions/16446665/c-read-from-csv-file – 463035818_is_not_an_ai May 25 '20 at 10:42
  • @idclev463035818 sorry about that, first post on stackoverflow. I just used a couple of getline's and it did the trick. Thanks for your help! – dacimovic May 25 '20 at 10:55

1 Answers1

0

you can use boost::splite function:

int func()
{
    ifstream RecordFile("records.txt"); 
    std::string line;
    while (!std::getline(RecordFile, line);)    
    {
        std::vector<string> vec;
        boost::split(vec, line, boost::is_any_of(","));

        Recordsarray[i].setRecords(vec);     

       i++;
       recordcounter++; 
    }

    RecordFile.close();            

    return recordcounter;
}
yaodav
  • 1,126
  • 12
  • 34