Nothing happens? For me, your program crashes.
'/0' on lines 33 and 37 should be '\0' (i.e. backslash not forward slash.)
With this fix your program runs for me but fails to find a match.
To help yourself, add diagnostic code, e.g.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
#include <math.h>
//User enters 2 character sequences(each doesn't exceed 100 characters).
//Print out how many times a word from the second sequence repeats in the first.
//For example, "My name is Bill.I am a programmer." and "am", the output will be 3.
//For "My name is Bill.I am a programmer." and "name", the output will be 1.
using namespace std;
int main()
{
int i = 0;
int j = 0;
char*a = NULL;
char*b = NULL;
a = new char[100];
b = new char[100];
cout << "Enter the first character sequence: " << endl;
cin.getline(a,100);
cout << "Enter the word that you are looking for :" << endl;
cin.getline(b, 100);
int counter = 0;
int counter2 = 0;
string word="";
string worduser = "";
for (int p = 0; b[p]!= '\0'; p++)
{
worduser = worduser + b[p];
}
cout << "worduser = " << worduser << endl;
for (int o = 0; a[o]!= '\0'; o++)
{
if (a[o] >= 'a' && a[o] <= 'z' || a[o] >= 'A' && a[o] <= 'Z')
{
word = word + a[o];
cout << "test word = " << word << endl;
if (worduser == word)
{
cout << "match!" << endl;
counter2 = counter2 + 1;
}
else
{
cout << "reset word to \"\"" << endl;
word = ""; }
}
}
cout << "Your word is" << counter2 << "in the text"<< endl;
system("pause");
return 0;
}
|
Enter the first character sequence:
one two three
Enter the word that you are looking for :
two
worduser = two
test word = o
reset word to ""
test word = n
reset word to ""
test word = e
reset word to ""
test word = t
reset word to ""
test word = w
reset word to ""
test word = o
reset word to ""
test word = t
reset word to ""
test word = h
reset word to ""
test word = r
reset word to ""
test word = e
reset word to ""
test word = e
reset word to ""
Your word is0in the text |
Andy
PS I think you need to think a bit more about what's going on around lines 41-46
Even if you fix the over keen resetting of
word
, it might still not behave quite right. e.g. for the string "That green pen belongs to Tux the penguin" and searching for "pen" it would prob match the pen at the start of penguin rather than the pen towards the start of the sentence.
PPS Also...
1. the memory you're allocating on lines 22 and 23 is leaking (you could prob just use a buffer rather than new-ing (and deleting!!) the storage?)
2. with the help of standard routines you could reduce your code up a bit? e.g.
http://www.cplusplus.com/reference/cctype/isalpha/
3. You should kill your unused variables