0

I have never used istringstream before. I have only split lines before with 1 delimiter so I don't know how to use istringstream. I am splitting lines from a file that look like this:

Table, Wanted, 100

Car, For Sale, 5000

I need to split the strings and then create an array of structs. I have a struct set up already I just don't know how to split the strings. My struct is called item and has types: string type, bool sale, double price. For sale, I want it to say 1 if it is for sale and 0 if it is wanted. Basically, I want to split it so I can create new variables, type, sale, and price and then create a newItem{type, sale, price} in my item struct and go from there. An example of the code would be extremely helpful. Thanks so much.

klw_123
  • 9
  • 1
  • 5
  • 3
    Can you try your best first? Before we try ours? That's fair, right? – Drew Dormann Jan 20 '15 at 00:54
  • It seems you want to parse a csv file. Plenty of information about how to do that here: http://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c/ – Retired Ninja Jan 20 '15 at 00:59

1 Answers1

1

A simple method to split a string using a delimiter character is to use std::getline.

std::string line = "Table, Wanted, 100"; // Let's say you have read a line from file.
std::istringstream input{line};          // Create an input stream from string.

// Read all characters up until the delimiter ',' on each iteration.
for (std::string token; std::getline(input, token, ',');) {
    /* Do something with each token... */
}

Live example

Felix Glas
  • 15,065
  • 7
  • 53
  • 82