0
What I want:
From string: 24.5,0, 9, 8,FLB

Get  Time : 24.5
     CAN_ID: 0
     RCTBSTAT: 9
     R_L: 8
     RCTBSTAT_Convert: FLB

getline() and strtok() could not meet what I need. I read a csv file with the function getline() and it work perfectly fine.

However, it troubles me when I wanted to split the string acquired which is in the form of: 0.00222,0,FALSE,345vdd,FALSE,... and assign it to different variables.

Could you suggest any alternatives?

struct data
{
    double Time;    
    int CAN_ID;
    int RCTBSTAT;
    int R_L;
    unsigned char RCTBSTAT_Convert;
    unsigned char R_L_Convert;
    int TRD_ID;
    bool ALRT;
    bool NEW;
    bool EXTRAPOL;
    bool GHST_POS;
    int X_WDTH;
    int RCS;
    int REL_X;
    int REC_Y;
    int REL_VX;
    int REL_VY;
    int X_WDTH_Convert;
    float REL_X_Convert;
    float REL_Y_Convert;
    double REL_VX_Convert;
    double REL_VY_Convert;
};

int main(int argc, char *argv[])
{
    ifstream inFile(argv[1]);
    string line;
    string headline;
    string rowitems;
    int linenum=0 ;     
    getline (inFile, headline, '\n');   

    for (linenum=1; getline (inFile, line); linenum++)
    {  
        //cout << "\nLine #" << linenum << ":" << endl;
        istringstream linestream(line);
        istringstream headerstream(headline);
        ********
        **help**
        ********
    }
    return 0;
}
Jenson Jen
  • 31
  • 2

2 Answers2

4

You can try

#include <string>
#include <deque>
#include <vector>
#include "strtk.hpp"

std::string int_string = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15";
std::vector<string> int_list;
strtk::parse(int_string,",",int_list);

Then use the vector to assign to multiple variables

Edit: you can find the strtk.hpp here

Jonathan Bouchard
  • 423
  • 1
  • 4
  • 15
0

First - remove all spaces to make a string delimiter unified:

string base_str = "a, b, val1,FALSE, TRUE, 24.5";   
stringstream ab(base_str);
string buf;
string res_str;
while (ab >> buf)
    res_str+=buf;

It will be a string without unexpected tabs or spaces string res_str = "a,b,val1,FALSE,TRUE,24.5";
Then - split the string by needed delimiter to vector:

int split (
    const string& a_str,
    const string& a_sep,
    vector<string>& a_vect,
    const int a_maxcnt
    )
{
a_vect.clear();
size_t beg = 0;
int cnt = 0;

do
{
    size_t sep_pos = a_str.find(a_sep, beg);
    if (sep_pos == string::npos)
        sep_pos = a_str.length();

    string expr = a_str.substr(beg, sep_pos-beg);
    a_vect.push_back(expr);
    cnt++;
    beg = sep_pos+a_sep.length();
    if (a_maxcnt && cnt == a_maxcnt-1)
        break;
}
while (beg < a_str.length());
if (beg < a_str.length())
{
    string expr = a_str.substr(beg);
    a_vect.push_back(expr);
}
else if (beg == a_str.length()) {
    a_vect.push_back("");
}
return (int) a_vect.size();
}
ETech
  • 1,613
  • 16
  • 17