I'm trying to make a string code work but I can't seem to make it return the number of names in a string. The string should count the number of names in an array(i.e. John Doe would be 2) and return the value of names. I have the code below, and my attempt to implement it below that. I can't get it to return anything for me.
1 2 3 4 5 6 7 8 9 10 11 12 13
int parseName(string& name, string components[]){
int names = 1; // the number of name components - must be at least 1
int start = 0; // start from position 0;
int next;
do {
next = name.find(" ", start); // find NEXT space
if (next == string::npos){ // at end, family name
components[0] = name.substr(start,name.length()-start);
} else {
components[names] = name.substr(start, next-start);
start = next + 1; // start past the space
names++;
}
// Example program
#include <iostream>
#include <string>
usingnamespace std;
int parseName(string& name, string components[]);
int main()
{
string x="John Doe Smith";
string components[]={};
cout<<parseName(x,components);
}
int parseName(string& name, string components[]){
int names = 1; // the number of name components - must be at least 1
int start = 0; // start from position 0;
int next;
do {
next = name.find(" ", start); // find NEXT space
if (next == string::npos){ // at end, family name
components[0] = name.substr(start,name.length()-start);
} else {
components[names] = name.substr(start, next-start);
start = next + 1; // start past the space
names++;
}
} while (next != string::npos);
return names;
}
For one, you never gave the string components, a size. Plus, when you send the array to a function, you must let the function know the size. This works. It gives 4, as an answer.
// Example program
#include <iostream>
#include <string>
usingnamespace std;
int parseName(string& name, string components[]);
int main()
{
string x="John Doe Allan Smith";
string components[15]={};
cout<<parseName(x,components);
cout << endl;
}
int parseName(string& name, string components[15]){
int names = 1; // the number of name components - must be at least 1
int start = 0; // start from position 0;
int next;
do {
next = name.find(" ", start); // find NEXT space
if (next == string::npos){ // at end, family name
components[0] = name.substr(start,name.length()-start);
} else {
components[names] = name.substr(start, next-start);
start = next + 1; // start past the space
names++;
}
} while (next != string::npos);
return names;
}
Doesn't seem to be so, but it's a good habit to get into. This small program of yours, may get away without, but maybe because you're only dealing one name.