Hi,
I am storing strings in '|' delimited format in a text file. Each new line represents a new record.
for instance

|Name|Age|Favcolour|
|Name2|Age2|Favcolour2|

I'm using a string vector to hold the tokens as they're pulled from the ifstream, However if one of the fields has not been filled in (which I have to presume could happen) the vector only contains the tokens that actually existed (weren't empty).

So for instance

|John||Turquoise blue|

causes the program to crash as I try and convert the string "turquoise blue" to an int. I realise my design is totally amateurish, but I've already spent a fair bit of time getting this to work, and have come to a halt on this.

I could just stick in a character to represent an empty field, such as # when I'm saving the file, and then check for it when outputting the data, but is their a smarter way to do this?

The function is below

best,
alasdair

PERSON strSplitter(const string& s, const string& delims) {
  int i=0;
  std::vector<string> fields;
  string::size_type lpos = s.find_first_not_of(delims, 0);
  string::size_type pos = s.find_first_of(delims, lpos);
  while (string::npos != pos || string::npos != lpos) {
    fields.push_back(s.substr(lpos, pos - lpos));
    lpos = s.find_first_not_of(delims, pos);
    pos = s.find_first_of(delims, lpos);
    i++;
  }
  PERSON p;
  p.name.last = fields[0];
  p.name.first = fields[1];
  p.name.title = fields[2];
  p.dob.d = atoi(fields[3].c_str());

Add a specific test to detect the double "||" in the file, and act accordingly?

that seems pretty smart, I'm giving it ago :-)

Just noticed your avatar
You should meet my lecturer - we're always pulling him up over the void main()s

As this is C++, you should be parsing each record using a stringstream and getline(). Here's minimal code to get you started.

string record, field;
getline( cin, record );
{
  stringstream fields( record );
  for (
    int field_index = 0;
    getline( fields, field, '|' );
    field_index++
    )
    store_field( field_index, field );
}

The store_field() function takes an index and a string. Depending on what the indexed field should contain, the function should convert the string to it (use another stringstream for the conversion). If the string is empty, then use a default.

Hope this helps.

BIG EDIT:

so sorry, I know see that I was debugging the wrong source file, not the updated one. Your algorithm works perfectly, can't thank you enough :-)

I'm going to read up on string streams tonight and the whole stream idea in general as it's clearly something I need to know about

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.