What I want to do is read a string with a bunch of words seperated by a delimiter, in this case the delimiter is a tilda ('~'). The number of words in the string i want to split is always unknown. I want to store the words in a structure where I can print out each word using a for loop like I have in my code. This program runs just the way I want it to, i'm just wondering if anyone could tell me a better way of doing it. I would like to avoid allocating more memory then I have to.
Thanks
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// d1 and d2 are used to track the delimiter
int d1 = 0, d2 = 0, i = 0;
// here is the string with '~' as the delimiter
string line = "ID~ARCHIVE~AREA~CASEBOX~CHAR~CIPOCONF";
// for loop to count number of delimiters in string
for(int t=0; t<= line.length(); t++)
if(line[t] == '~')
i++;
// set the # of elements for string array based on for loop above
string* fields = new string[i+1];
// reset i to 0 for the while loop
i = 0;
// while loop creates and assigns substring to array based
// on location of the delimiter
while(line.find("~",d1)!= string::npos)
{
d2 = line.find("~",d1);
fields = line.substr(d1,d2-d1);
d1 = d2;d1++;i++;
}
// puts the last element of the string in array
fields = line.substr(d1,line.length());
// prints the seperated words
for(t = 0; t <= i; t++)
{
cout << fields[t] << endl;
}
return 0;
}
Thanks
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
// d1 and d2 are used to track the delimiter
int d1 = 0, d2 = 0, i = 0;
// here is the string with '~' as the delimiter
string line = "ID~ARCHIVE~AREA~CASEBOX~CHAR~CIPOCONF";
// for loop to count number of delimiters in string
for(int t=0; t<= line.length(); t++)
if(line[t] == '~')
i++;
// set the # of elements for string array based on for loop above
string* fields = new string[i+1];
// reset i to 0 for the while loop
i = 0;
// while loop creates and assigns substring to array based
// on location of the delimiter
while(line.find("~",d1)!= string::npos)
{
d2 = line.find("~",d1);
fields = line.substr(d1,d2-d1);
d1 = d2;d1++;i++;
}
// puts the last element of the string in array
fields = line.substr(d1,line.length());
// prints the seperated words
for(t = 0; t <= i; t++)
{
cout << fields[t] << endl;
}
return 0;
}