Split String for C++

I have a file of names:

middle@first@last

I need to read the file and split the string into an array, separating the characters by "@".

How can I do this? Thanks!
You could use something like this:
http://cplusdev.com/pages/tutorials/fileiocsv.html

Change the file to your names.txt and on the lines where it has
 
char* comma = strchr(buffer, ',');
etc

Change them to:
 
char* comma = strchr(buffer, '@');


This is just one of the ways you could try to implement it.
Both those suggestions are for C, not C++.

In C++, use the string class and member functions to find() a specific substring's (or character's) position and then use substr() to get the piece of the string you want.

Alternately, and what I would do, is use a stringstream to parse the string into pieces.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

...

  string line;
  while (getline( myfile, line ))
  {
    string first, middle, last;
    istringstream liness( line );
    getline( liness, middle, '@' );
    getline( liness, first,  '@' );
    getline( liness, last,   '@' );

    cout << "Full name is: " << first << " " << middle << " " << last << ".\n";
  }

Hope this helps.
Boost has a nifty algorithm for this in its string algorithms library: http://www.boost.org/doc/libs/1_41_0/doc/html/string_algo/usage.html#id1701774


1
2
3
4
#include <boost/algorithm/string.hpp>
...
  vector<string> results;
  boost::split(results, line, boost::is_any_of("@"));
Topic archived. No new replies allowed.