-1

So I have some code which reads from a file and separates by the commas in the file. However some things in the file often have spaces after or before the commas so it's causing a bit of a problem when executing the code.

This is the code that I which reads in the data from the file. Using the same kind of format I was wondering if there was a way to prepare for this spaces

while(getline(inFile, line)){
        stringstream linestream(line);
        // each field of the inventory file 
        string type;
        string code;
        string countRaw;
        int count;
        string priceRaw;
        int price;
        string other;
        // 
        if(getline(linestream,type,',') && getline(linestream,code,',')
        && getline(linestream,countRaw,',')&& getline(linestream,priceRaw,',')){
            // optional other
            getline(linestream,other,',');
            count = atoi(countRaw.c_str());
            price = atoi(priceRaw.c_str());
            StockItem *t = factoryFunction(code, count, price, other, type);
            list.tailAppend(t);
       }
    }
Hidden
  • 101
  • 9
  • 1
    [CSV files](https://en.wikipedia.org/wiki/Comma-separated_values) are actually harder to parse than it appears on the surface, and can have many weird corner-cases that are hard to work by. My recommendation is that you try to find a library to handle the parsing of the files instead. – Some programmer dude Apr 13 '16 at 16:37
  • It's unclear what you are trying to ask. What output are you expecting and exactly what problem are you experiencing? – Biruk Abebe Apr 13 '16 at 16:37
  • I'm getting some data saved like this "data " and others like this " data" and others like this " data ", as you can see I just want rid of the spaces @bkVnet – Hidden Apr 13 '16 at 16:39
  • @Hidden _"I just want rid of the spaces"_ Check [this](http://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring) for this purpose please. – πάντα ῥεῖ Apr 13 '16 at 17:12

1 Answers1

0

The better approach for those kind of problems is a state machine. Each character that you get should act in a simple way. You don't state if you need spaces between words non delimited by commas, so I suppose you need them. I don't know what you need to do with double spaces, I suppose you need to keep things as are. So start reading one character at a time, there are two variables the start positions and the limit position. When you start you are determining the start position ( state 1 ). If you find any character different than the space character you set that start position to that character and you change your state to ( state 2 ). When in state 2 when you find a non space character you set the limit position to the next position than the character you found. If you find a comma character you get the string that begins form start to limit and you change again into state 1.

George Kourtis
  • 2,381
  • 3
  • 18
  • 28