This program should seperate a string such as 2/3 into 2 and 3. When I run it and enter data for the string, I get an error message, the one that asks you if you want to send an error report.
I got the example from a book but the book used char types and I tried to use string types.
Note: use_String_Parser() is the equivelent if main. (this is called by another program.
#include
"stdafx.h"#include <String.h>
void
use_String_Parser();class
StringParser{private
: //Data Members int m_pos;string m_input_str;
string m_delimeters;
public
: //Public Functionsstring *get();
int more() {return (m_input_str[m_pos] != '\0');} void reset() {m_pos = 0;} //ConstructorsStringParser(string m_inp, string delim) {m_input_str = m_inp; m_delimeters = delim; m_pos = 0;}
StringParser(string inp) {m_input_str = inp; m_delimeters =
','; m_pos = 0;}};
void
use_String_Parser(){string v_input_string;
string *p;
//Delayed: {StringParser parser(input_str, "/");}cout <<
"Enter input line: ";getline(cin, v_input_string);
StringParser parser(v_input_string,
"/"); while (parser.more()){p = parser.get();
cout << p << endl;
delete [] p;}
}
string *StringParser::get(){
int j = 0;string *new_str;
new_str =
new string; while (strchr(m_delimeters.c_str(), m_input_str[m_pos]))++m_pos;
while (m_input_str[m_pos] != '\0' && !strchr(m_delimeters.c_str(), m_input_str[m_pos]))new_str[++j] = m_input_str[++m_pos];
new_str[j] =
'\0'; return new_str;}

new and strings
gheese
std::getline()
index of source string is less than string size
dynamically allocated string object is sized correctly
Kuphryn
carina9138
string *new_str = new string;
makes new_str a pointer to a string object, not a pointer to an array of characters. In addition, as Kuphryn points out, you cannot index characters the way you're doing because you'd be indexing an array of string objects (of which there is only the one you allocated). Furthermore, the corresponding delete should be delete p, not delete[] p.
It's okay to return string objects instead a pointer to string objects. The whole point of using string is that it manages the "pointing to an array of characters" business for you and makes strings act more like first-class objects within the language. You should use string::append() to add characters to the string.
If it helps, here's a simpler implementation that I use on relatively short 8-bit character strings. It is patterned after System.String.Split in the .NET framework.
vector<string> Split( const string& input, const string& delimiters )
{
vector<string> arr;
char* tokenizeCopy = strdup( input.c_str() );
char* pos = tokenizeCopy;
char* token;
do
{
token = strtok( pos, delimiters.c_str() );
pos = 0;
if( token != 0 )
{
arr.push_back( token );
}
} while( token != 0 );
free( tokenizeCopy );
return arr;
}