Good day. I've written this program to print the amount of times a character is found,and am using for loops to do so. However,when I compile and run the program,it doesn't seem to find the characters. Here's the output I get.
1 2 3 4 5 6
Enter your tweet (160 character limit) here: LOL I don't know
Finding LOL's
laughing out loud showed up 0times.The count is :
Process returned 0 (0x0) execution time : 10.204 s
Press any key to continue.
I'd appreciate any help I can get with this. The code for the program is below.
#include <iostream>
#include <string>
usingnamespace std;
int main() {
constunsigned length(160);
string tweet;
string plaintexttweet;
int pos;
int lolcount;
int a = 0;
const string LOL = "laughing out loud";
//IO here
cout << "Enter your tweet (160 character limit) here: ";
getline(cin,tweet);
//size change here
if(tweet.size() > length){
tweet.resize(length);
}
//Copying value to other variables
plaintexttweet = tweet;
//Find and replace in plaintext tweet
lolcount = plaintexttweet.find("LOL");
for (int a = 0; a == lolcount; a++)
{
cout << "Finding LOL's"<<endl;
}
cout << LOL << " showed up " << a << "times.";
cout << "The count is :" << endl;
return 0;
}
your logic is a mess.
lolcount is the position in the string where the first time it found the letters is, the index into the string, except it could be string::npos if not found at all.
for (a = 0 to the first place in the string where you found the letters, a++)
cout spam text
cout << a which is zero because the one in the loop is scoped and died, its the main-scoped version of a, and explains the idea behind 'lets not have the same variable in the same neighborhood but in 2 not obvious scopes' defensive programming concept. Don't do this to yourself.
so it prints zero.
what should it do?
it should go into the string 1 past the place it found the last copy of the text and search again. Until it gets string::npos. Count the number of times this happens.
In line 24 the use of "lolcount" is misleading. The ".find"function returns a position, so the "pos" you defined would be much better for the variable. Also more descriptive.