Is there a way to seperate these? Say an address like 123 Fake St., is it possible to seperate the number, the street name, then st.?
And what would this be? Int, Char, etc.
Printable View
Is there a way to seperate these? Say an address like 123 Fake St., is it possible to seperate the number, the street name, then st.?
And what would this be? Int, Char, etc.
You can use what is called a "token" I haven't programed in a while so I'm not quite sure how to use it still...but it will read a string up to a space or other desiginated character. If you do a search you should be able to find out how to use it...if not i'll find my book tomorrow and look it up for you...
Use strtok
The output :Code:char fullstring[100] = "123 Fake St.";
char *p;
p = strtok(fullstring, " ");
int i = 0;
while (p != NULL)
{
cout << "Token " << ++i << " : " << p << endl;
p = strtok(NULL, " ");
}
Token 1 : 123
Token 2 : Fake
Token 3 : St.
Here is another example.
Code:#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::cout;
using std::iter;
using std::string;
vector<string> Split( const string&);
void PrintVec ( const vector<string> &);
int main()
{
vector<string> Token;
string address;
cout << "Enter an address: ";
getline(cin, address);
cout << "The address you entered is: " << address << endl;
Token = Split(address);
PrintVec(Token);
return 0;
}
vector<string> Split (const string & s)
{
vector<string> ret;
string::size_type i = 0;
while ( i != s.size() )
{
//skip leading blanks
while ( i != s.size() && isspace(s[i]) ) ++i;
//find end of next word
string::size_type j = i;
while ( j != s.size() && !isspace(s[j]) ) ++j;
//if we found some whitespace characters
if ( i != j)
{
//copy from s starting at i and taking j - i characters
ret.push_back( s.substr( i , j - i) );
i = j;
}
}
return ret;
}
void PrintVec (const vector<string> & Token)
{
vector<string>::const_iterator i = Token.begin();
while ( i != Token.end() )
{
cout << "Token: " << *i << endl;
i++;
}
}