I am nearly done with this short program using pointers to count how many times a given character is typed in a string.
The problem is, it only works for single words. If I try typing a sentence, the code automatically executes and does not allow me to pick letter, instead citing the second word and reporting that it counts '0' times.
For example, a sample output for a word is:
1 2 3 4 5
Please input the string:
hello
Please input the character to count:
l
The letter l appears 2 times.
vs.
1 2 3 4
Please input the string:
hello, my name is lolzgeorge.
Please input the character to count:
The letter my appears 0 times.
// 12/07/2010
// Assignment 5
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main ()
{
int count(0);
char strg1[100],strg2[100]; //Arbitrary length, eg, sentences are rarely over 100 characters, letter count, etc.
char *ptr1(strg1), *ptr2(strg2);
cout<<"Please input the string:"<<endl;
cin>>strg1;
cout<<"Please input the character to count:"<<endl;
cin>>strg2;
while ((ptr1=strstr(ptr1,ptr2)) != NULL)
{
count++;
ptr1++;
}
cout<<"The letter "<<strg2<<" appears "<<count<<" times."<<endl;
system ("pause");
return 0;
}
Whats happening here is that the << operator stops when it reaches whitespace. This means that only the first word in a sentence gets stored in strg1. when you use cin << again, there is still data to be read from cin, so it stores the next word in strg2. One solution (there are probably others) is to use cin.getline instead. In that case the syntax would be:
1 2
cin.getline(strg1,100) // the 100 here denotes the maximum number of characters to read.
// i've set it to the same size as the char array so it won't overflow
I would also suggest you change the second cin << to something else, so that the user can't input more than one character (unless you want them to be able to). Try something like this:
Yes sorry, i realise what happened now, the function strstr expects two arrays of chars whereas you're only providing one array and one single char, fortunately there's also a strchr function http://www.cplusplus.com/reference/clibrary/cstring/strchr/ , have a look at that and see if you can figure out what to change.