-
October 9th, 2013, 11:43 AM
#1
C++ Program help for a Newbie
Hello everyone. I am taking an online c++ class which offers very little instruction. I am brand new to programing and I am struggling with an assignment. If you would be kind enough to help me it would be greatly appreciated.
Here is the problem: I am trying to write a program that ask the user to enter a sentence and then a word to be searched for in the sentence. The program must then search for the word in the sentence in a loop and continue to output each place the word is found. For example if the sentence is : I like pickles, pickles, pickles
and you searched for pickles it would return pickles found at 7, pickles found at 16, pickles found at 25.
I am having trouble writing the equation to make the find keep searching after each occurrence of the word being searched.
Here is the code I have so far
HTML Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string paragraph;
cout << "Please enter your paragraph:";
getline (cin,paragraph);
cout << "Hello, your paragraph is " << paragraph << "!\n";
cout << "The size of your paragraph = " << paragraph.size() << " characters. \n\n";
string word;
cout << "Please enter the word you are searching for:";
getline (cin,word);
cout << "Hello, your word is " << word << "!\n";
size_t position = paragraph.find(word);
bool wordsearch = true;
while (paragraph.find(word) != string::npos) {
if (paragraph.find(word) == string::npos)
cout << "" << word << " does not exist in the sentence" << endl;
size_t position = paragraph.find(word);
if (position!=string::npos)
cout << "The word " << word << " is found at: " << position << '\n';
position=paragraph.find((word),position+1);
if (position!=string::npos)
cout << "The word " << word << " is also found at " << position << '\n';
position=paragraph.find((word),position+1);
if (position!=string::npos)
cout << "The word " << word << " is also found at: " << position << '\n';
position=paragraph.find((word),position+1);
if (position!=string::npos)
cout << "The word" << word << "is also found at: " << position << '\n';
else
cout << "There are no more occurences of the word " << word << '\n';
system ("pause");
}while (wordsearch = true);
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|