cskwrd
cskwrd

Reputation: 2885

read words from line in C++

I was wondering if there was a way to read all of the "words" from a line of text.

the line will look like this: R,4567890,Dwyer,Barb,CSCE 423,CSCE 486

Is there a way to use the comma as a delimiter to parse this line into an array or something?

Upvotes: 2

Views: 9970

Answers (2)

Ravindra
Ravindra

Reputation: 9

//#include sstream with angular braces in header files 

std::string str = "R,4567890,Dwyer,Barb,CSCE 423,CSCE 486";

std::istringstream iss(str,istringstream:in);

vector<std::string> words;

while (std::getline(iss, str, ','))
  words.push_back(str);

Upvotes: 0

hrnt
hrnt

Reputation: 10142

Yes, use std::getline and stringstreams.

std::string str = "R,4567890,Dwyer,Barb,CSCE 423,CSCE 486";

std::istringstream iss(str);
std::vector<std::string> words;

while (std::getline(iss, str, ','))
  words.push_back(str);

Upvotes: 12

Related Questions