Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
C++ Problem (Trying to split a string)?
I am trying to use getline,cin to receive a two word string, and then split the string into two one word strings, must the same way the old text adventures of the 1980's did. However, I can't seem to figure it out. It should look like this:
What shall I do? GO WEST
Main reports that you typed
go for a verb.
west for the noun.
My result is
Main reports that you typed
for a verb.
go west for the noun.
This is the intended code.
int main(int argc, char *argv[])
{
while (death>0){
string answer,verb,noun,separator;
cout << "What shall I do? ";
getline (cin,answer);
for(unsigned int i=0;i<answer.length();i++){ // Convert to Lowercase
answer[i] = tolower(answer[i]);}
// Split answer in 2 variables
size_t i = answer.find(separator);
if(i != string::npos){
size_t y = 0;
if(!answer.empty()){
while(y != i){
verb += answer[y++];
}
y+= separator.length();
while(y != answer.length()){
noun+=answer[y++]; //creating noun string
}
}
cout << "Main reports that you typed " << endl;
cout << verb << " for a verb." << endl;
cout << noun << " for the noun.\n\n" << endl;
}
Any help would be appreciated.
system("PAUSE");
return EXIT_SUCCESS;
}
}
2 Answers
- oopsLv 69 years agoFavorite Answer
If you have boost, and you should, there is a function called split. If not, then you can use string streams. Here's an example of both:
- CarlLv 69 years ago
Your problem is you declare the string variable "separator" but you never assign it a value. Try inserting the line:
separator = " ";
Another way to do it (the way I would do it) is something like this:
int len = answer.length();
int separated = 0;
for (i = 0; i < len; i++)
if (separated == 0)
if (answer[i] == ' ') // one blank space between apostrophes
separated = i;
else verb[i] = answer[i];
else noun[i - separated - 1] = answer[i];