- #1
twotaileddemon
- 260
- 0
I think I am close but I really cannot figure out how to get the function to work properly. I need to have the user type in several lines and display a count of how many times the word "duck" has been used. I am not sure I am using the strstr right either... any help would be appreciated.
-----------
#include <iostream>
#include <string>
using namespace std;
// Write a function to display a count of the number
// of times the word "duck" appears in an array of strings.
//Prototype
int getDuckCount (string word[], int arraySize);
int main ( )
{
// Declaration
int count;
string line[100];
int size = 100;
// Input
cout << "Enter some lines to find a count of how many times"
<< " the word duck appears. Hit enter on a blank line to terminate." << endl;
for (int index = 0; ;index++)
{
getline (cin, line[index]);
if (line[index] == "") break;
count = getDuckCount (line[], size);
}
//Output
cout << "The word duck appears " << count << " times. Quack!" << endl;
return 0;
}
int getDuckCount (string word[], int arraySize)
{
int duckCount = 0;
char * duck;
for (int index = 0; ;index++)
{
duck = strstr (word[index], "duck");
if (word[index] == "") break;
if (word[index] == duck) duckCount++;
}
return duckCount;
}
-----------
#include <iostream>
#include <string>
using namespace std;
// Write a function to display a count of the number
// of times the word "duck" appears in an array of strings.
//Prototype
int getDuckCount (string word[], int arraySize);
int main ( )
{
// Declaration
int count;
string line[100];
int size = 100;
// Input
cout << "Enter some lines to find a count of how many times"
<< " the word duck appears. Hit enter on a blank line to terminate." << endl;
for (int index = 0; ;index++)
{
getline (cin, line[index]);
if (line[index] == "") break;
count = getDuckCount (line[], size);
}
//Output
cout << "The word duck appears " << count << " times. Quack!" << endl;
return 0;
}
int getDuckCount (string word[], int arraySize)
{
int duckCount = 0;
char * duck;
for (int index = 0; ;index++)
{
duck = strstr (word[index], "duck");
if (word[index] == "") break;
if (word[index] == duck) duckCount++;
}
return duckCount;
}