RaGa__M
RaGa__M

Reputation: 2571

using getline() while separating comma didn't work

I have read a CSV file that has line ending character as '\r', the reading operation done successfully, but the problem started when i pass the read line in to the while(getline(ss,arr2,',')) for separating comma..it does work properly for the first line but all the next iterations are empty(i.e)it has been failing to separate the comma in the string.

int main()
{
    cout<<"Enter the file path :";
    string filename;
    cin>>filename;
    ifstream file;
    vector<string>arr;
    string line,var;
    stringstream content;
    file.open(filename.c_str(),ios::in );
    line.assign((std::istreambuf_iterator<char>(file)),
                 std::istreambuf_iterator<char>());
    file.close();
    string arr2;
    stringstream ss;
    content<<line;
    //sqlite3 *db;int rc;sqlite3_stmt * stmt;
    int i=0;
    while (getline(content,var,'\r'))
    {
        ss.str(var);//for each read the ss contains single line which i could print it out.
        cout<<ss.str()<<endl;
        while(getline(ss,arr2,','))//here the first line is neatly separated and pushed into vector but it fail to separate second and further lines i was really puzzled about this behaviour.
        {
            arr.push_back(arr2);
        }
        ss.str("");
        var="";
        arr2="";
        for(int i=0;i<arr.size();i++)
        {
            cout<<arr[i]<<endl;
        }
        arr.clear();
    }
    getch();
}

what went wrong in the above...I see nothing right now:(

Upvotes: 0

Views: 247

Answers (1)

Holt
Holt

Reputation: 37606

The stringstream::str method does not reset / clear the internal state of the stream. After the first line, the internal state of ss is EOF (ss.eof() returns true).

Either use a local variable inside the while loop:

while (getline(content,var,'\r'))
{
    stringstream ss(var);

Or clear the stream before ss.str:

ss.clear();
ss.str(var);

Upvotes: 2

Related Questions