1

I want to split the lines of a .csv file in which data is comma-separated. I wrote the following function

const char DELIMITER = ',';

vector <string> split (string input)
{
    stringstream SS(input);
    vector <string> splitedWords; 
    string word;

    while (getline(SS, word, DELIMITER))
        splitedWords.push_back(word); 

    return splitedWords;
}

It works properly as long as there is no space character in the line but when a phrase includes a space character the function ends working. See the model inputs and outputs;

intput: this,is,a,test
output: {this, is, a, test} --> TRUE output

input: this,is not,a,test
output: {this, is} --> FALSE output --> Desired output: {this, is not, a, test}
Mahdi
  • 27
  • 5
  • 1
    [Works for me](https://wandbox.org/permlink/21t4dnp83N50mFFv). Please provide [mcve] – Yksisarvinen Oct 23 '20 at 10:23
  • @Yksisarvinen it works if you initialize the string in the main body but in the case that you want to read a line from stdin or a file, it doesn't work because the program doesn't read the whole line and reads until the first whitespace. – Mahdi Oct 23 '20 at 11:29
  • Ah, so your problem is related to the code you didn't show. Please read this: [How to read line by line or a whole text file at once?](https://stackoverflow.com/questions/13035674/how-to-read-line-by-line-or-a-whole-text-file-at-once#13035743) (can't mark as a duplicate, because I already voted to close). – Yksisarvinen Oct 23 '20 at 11:34
  • @Yksisarvinen Actually that part of my code is OK. I'm sure about it. – Mahdi Oct 23 '20 at 12:04
  • This function works correctly. It doesn't have any issues with inputs containing spaces. Your problem is with the input you provide to the function. The string you provide to the function is already splitted, so you need to fix the way you obtain that string. And this is done by replacing `>>` with `std::getline()` – Yksisarvinen Oct 23 '20 at 12:41

0 Answers0