I'm a newbie C++ programmer. I've written a basic emotion checker that reacts based on your reply that gets fetched from an array. I'm wondering how to make it so that the replies work in both upper and lower case when typed in? E.g. when the user types in "happy" or "Happy" both would work. I've read about switch statements and toupper/tolower but I'm lost on how to implement these for my code. Here it is:
// Array of emotions
string positive[] = {"happy", "pleased", "joyful", "excited", "content", "cheerful", "satisfied", "positive"};
string negative[] = {"unhappy", "sad", "depressed", "gloomy", "down", "glum", "despair", "negative"};
string reply;
cout << "Please state your current emotions." << endl;
cin >> reply;
for (int i = 0; i < 10; i++)
if (reply == positive[i])
{
cout << "I am glad to hear that!" << endl;
}
else if (reply == negative[i])
{
cout << "I am sorry to hear that." << endl;
}
You would want to add a step in to process the string reply after reading it in.
One solution would be to iterate over the length of reply and call tolower on each character in the string.
An example modified from http://www.cplusplus.com/reference/cctype/tolower/
int i = 0;
while (reply[i]) {
c=reply[i];
reply[i] = tolower(c);
i++;
}
Then when you compare the strings you don't need to worry about case.
First of all, write a function named equals to compare two world is the same or not by convert all character of a string to lowercase. example:
bool equals(string status, string userInput)
{
//lowercaseStatus = convert userInput to lowercase
//lowercaseUserInput = convert status to lowercase
return lowercaseStutus == lowercaseUserInput;
}
Then use the function in for loop:
for (int i = 0; i < 10; i++)
if (equals(positive[i],reply))
{
cout << "I am glad to hear that!" << endl;
}
else if (equals(negative[i],reply))
{
cout << "I am sorry to hear that." << endl;
}
Related
here is some fragment of my code. Can anyone help me? On how to make so the mask of the password is delayed by a second or two before it replaces the password with '*'?
struct adminInfo
{
string adminID;
string adminName;
string adminPassword;
};
void create_admin (adminInfo ad [], int &count)
{
char pass = 0;
const char BACKSPACE = 127;
const char RETURN = 10;
cout << " **************************************" << endl;
cout << " REGISTER ADMINISTRATOR" << endl;
cout << " **************************************" << endl;
cout << " Enter admin registration number (ID) : "; cin >> ws;
getline (cin, ad[count].adminID);
cout << " Enter admin full name : "; cin >> ws;
getline (cin, ad[count].adminName);
cout << " Please create your password : ";// cin >> ws;
//getline (cin, ad[count].adminPassword)
while ((pass=getch(void)) != RETURN)
{
if (pass == BACKSPACE)
{
if (ad[count].adminPassword.length() != 0)
{
cout << "\b \b";
ad[count].adminPassword.resize(ad[count].adminPassword.length() - 1);
}
}
else
{
ad[count].adminPassword += pass;
cout << "*";
}
}
count++;
}
Side note: Should std::endl always be used?
Also it might be easier for me to answer if I knew what libraries you were using. For the sake of simplicity I will presume you use the standard C++ library iostream for cout etc conio.h for getch() string for string and namespace std.
If you don't mind the last character being seen, you could literally just wait for the user input like this:
while ((pass = getch()) != RETURN) {
/* Making length variable so I don't have to call length() function multiple times and it looks cleaner */
int length = ad[count].adminPassword.length()
/* Using bigger than zero just to make it more explicit */
if (length > 0) {
/* Change last character to asterisk */
cout << "\b \b*";
}
if (pass == BACKSPACE) {
if (length > 0) {
cout << "\b \b";
ad[count].adminPassword.resize(length - 1);
}
} else {
ad[count].adminPassword += pass;
/* Instead of asterisk as that is now changed at every keypress after first input */
cout << pass;
}
}
If you wish to actually wait you could just include <windows.h> (or unix equivalent) and use Sleep(milliseconds) function like this in the else statement:
cout << pass;
ad[count].adminPassword += pass;
Sleep(Time in milliseconds)
cout << "\b \b*";
But this will wait the time in milliseconds to print out the next value and will give a pretty confusing and questionable output if you type above 3 wpm.
This is the best that I could think of, I'm not that knoweledgeable about C++ so sorry if I could not answer your question well enough.
I'm presuming you could do something with multithreading to make it wait while taking input. But as I said I do not know much about C++ so I will leave that to someone smarter than me ;D.
I've been struggling with a homework assignment that counts the amount of instances a uppercase letters, lowercase letters, and numbers in a string. appears in a string.
I'm using a one-dimensional array with a constant size of 132 to store the entered string, and I need to use two functions. One needs to count the amount of letter occurrences in the string and the other function will execute the output something similar to above. I'm struggling most with the letter counting aspect of the program itself.
Currently, this is what my current homework resembles for the most part. It's a work in progress (of course) so errors in the code are very likely.
void LetterCount(char c_input[], int l_count)
{
// code to count letters
}
void CountOut(//not sure what should go here yet until counting gets figured out)
{
// code that handles output
}
int main()
{
const int SIZE = 132;
char CharInput[SIZE];
int LetterCount = 0;
cout << "Enter a string of up to 132 characters in size: ";
cin.getline(CharInput, SIZE);
cout << "You entered: " << CharInput << endl;
Count(CharInput);
CountOut(//not sure what goes here yet);
return 0;
}
The output would look something like:
a - 2
b - 1
c - 1
d - 0
e - 1
etc...
I've tried some experimentation with for loops to count the letters and have seen some examples of the function gcount(), but I haven't gotten anything to work. Does anyone have a suggestion as to how I would count the letters in an inputted string?
map is a very efficient data structure here
#include <iostream>
#include <map>
using namespace std;
int main(){
string str = "a boy caught 2 fireflies";
map<char, int> str_map;
for(auto x : str) ++str_map[x];
for(auto x : str_map) cout << x.first << ' ' << x.second << '\n';
}
What you want is to build a simple histogram, and it's pretty easy to do. Since what you're looking at is chars, and there can be 256 possible values of an 8-bit char (in practice your input string probably uses less, but we'll be conservative here because memory is cheap), you'll want to start with an array of 256 ints, all of them initialized to zero. Then iterate over the chars your string, and for each char in your string, use that char-value as an offset into the array(*), and simply increment that item in the array.
When you're done, all that remains is to iterate over the ints in the array and print out the ones that are non-zero, and you're done.
(*) you may want to cast the char to unsigned char before using it as an offset into the array, just to avoid any chance of it being interpreted as a negative array-index, which would result in undefined behavior (this is only an issue if your input string contains ASCII characters 128 and higher, so it may not matter in your case, but it's always good form to make code that does the right thing in all cases if you can)
As Jeremy frisner said you're building a histogram, but I disagree with the types used.
You'll want to declare your histogram like so:
size_t histogram[sizeof(char)*CHAR_BIT] = {0};
The size_t because you might overflow without it, and you need enough space if it's a nonstandard byte size.
As for printing it out. You should take a look at an ASCII table and examine which values you need to print out.
You could do it by comparing c-strings with other c-strings. But with chars and strings you can get errors like: "const *char cant be compared with strings". So you'll have to compare each c string(array) index with other c string indexes. In this program I use if statements to look for certain vowels. The way it works is that each "string alphabet_letter" is equal to it's respective lowercase and capital letters (for comparison). this is a very redundant way to do it and, if you want to count all total letters, perhaps you should try a different way, but this method doesn't use very complicated methods that require deeper understanding.
using namespace std;
int main(){
int vowel;
string A = "aA";
string E = "eE";
string I = "iI";
string O = "oO";
string U = "uU";
string str;
string str1;
bool userLength = true;
int restart = 0;
do{
cout << "Enter a string." <<endl;
getline(cin, str);
int VowelA = 0;
int VowelE = 0;
int VowelI = 0;
int VowelO = 0;
int VowelU = 0;
for(int x = 0; x < 100; x++){
if(restart == 1){
restart = 0;
x = 0;
}
if(A[0] == str[x]){
VowelA = VowelA + 1;
}
if(E[0] == str[x]){
VowelE = VowelE + 1;
}
if(I[0] == str[x]){
VowelI = VowelI + 1;
}
if(O[0] == str[x]){
VowelO = VowelO + 1;
}
if(U[0] == str[x]){
VowelU = VowelU + 1;
}
if(A[1] == str[x]){
VowelA = VowelA + 1;
}
if(E[1] == str[x]){
VowelE = VowelE + 1;
}
if(I[1] == str[x]){
VowelI = VowelI + 1;
}
if(O[1] == str[x]){
VowelO = VowelO + 1;
}
if(U[1] == str[x]){
VowelU = VowelU + 1;
}
int strL = str.length();
if(x == strL){
cout << "The original string is: " << str << endl;
cout << "Vowel A: "<< VowelA << endl;
cout << "Vowel E: "<< VowelE << endl;
cout << "Vowel I: "<< VowelI << endl;
cout << "Vowel O: "<< VowelO << endl;
cout << "Vowel U: "<< VowelU << endl;
cout << " " << endl;
}
}
char choice;
cout << "Again? " << endl;
cin >> choice;
if(choice == 'n' || choice == 'N'){userLength = false;}
if(choice == 'y' || choice =='Y')
{
restart = 1; userLength = true;
cin.clear();
cin.ignore();
}
//cout << "What string?";
//cin.get(str, sizeof(str),'\n');
}while(userLength == true);
}
/*
Sources:
printf help
http://www.cplusplus.com/reference/cstdio/printf/
This helped me with the idea of what's a vowel and whats not.
http://www.cplusplus.com/forum/general/71805/
understanding gets()
https://www.programiz.com/cpp-programming/library-function/cstdio/gets
Very important functional part of my program...Logic behind my if statements, fixed my issues with string comparison
What i needed to do was compare each part of one cstring with another c string
strstr compares two strings to see if they are alike to one another this source includes that idea-> https://www.youtube.com/watch?v=hGrKX0edRFg
so I got the idea: What is one c string was all e's, I could then compare each index for similarities with a c string whos definition was all e's.
At this point, why not just go back to standard comparison with strings? But you cant compare const chars to regular chars, so I needed to compare const chars to const chars
hence the idea sparked about the c strings that contained both e and E.
https://stackoverflow.com/questions/18794793/c-comparing-the-index-of-a-string-to-another-string
https://stackoverflow.com/questions/18794793/c-comparing-the-index-of-a-string-to-another-string
Fixed Error with using incremented numbers outside of involved forloop.
https://stackoverflow.com/questions/24117264/error-name-lookup-of-i-changed-for-iso-for-scoping-fpermissive
understanding the use of getline(cin, str_name)
https://stackoverflow.com/questions/5882872/reading-a-full-line-of-input
http://www.cplusplus.com/reference/istream/istream/getline/
http://www.cplusplus.com/forum/beginner/45169/
cin.clear - cin.ignore --fixing issue with cin buffer not accepting new input.
https://stackoverflow.com/questions/46204672/getlinecin-string-not-giving-expected-output
*/
I have been trying to fix this program for the past two days and it is proving to be quite troublesome. It is an assignment for my intro to C++ course and has given me nothing but trouble. I have searched this board, posted on Cplusplus.com and spent hours on Google, looking for some assistance.
Here is my problem. I have been given a program and need to add a few features to it:
I have to save the users entries.
I have to display an error message if the user enters the same entry twice.
Seems simple? Not for a beginner such as myself. Here is the code, with what I have attempted to add to it in order to meet the problem's requirements.
int main()
{
//declare variables
string origWord = "";
string letter = "";
char dashReplaced = 'N';
char gameOver = 'N';
int numIncorrect = 0;
string displayWord = "-----";
string letterGuess[26];
//get original word
do //begin loop
{
cout << "Enter a 5-letter word in uppercase: ";
getline(cin, origWord);
} while (origWord.length() != 5);
//clear the screen
system("cls");
//start guessing
cout << "Guess this word: " <<
displayWord << endl;
while (gameOver == 'N')
{
cout << "Enter an uppercase letter: ";
cin >> letter;
//Entry Storage and Error Message. This is my problem.
for (int x = 0; x < 26; x++)
{
letterGuess[x] = letter;
for (int i = x; i < 26; i++)
{
if (i != x)
{
if (letterGuess[x] == letterGuess[i])
{
cout << "Letter already entered. Choose another letter."
<< endl;
}
}
}
}
//search for the letter in the original word
for (int x = 0; x < 5; x += 1)
{
//if the current character matches
//the letter, replace the corresponding
//dash in the displayWord variable and then
//set the dashReplaced variable to 'Y'
if (origWord.substr(x, 1) == letter)
{
displayWord.replace(x, 1, letter);
dashReplaced = 'Y';
} //end if
} //end for
//if a dash was replaced, check whether the
//displayWord variable contains any dashes
if (dashReplaced == 'Y')
{
//if the displayWord variable does not
//contain any dashes, the game is over
if (displayWord.find("-", 0) == -1)
{
gameOver = 'Y';
cout << endl << "Yes, the word is "
<< origWord << endl;
cout << "Great guessing!" << endl;
}
else //otherwise, continue guessing
{
cout << endl << "Guess this word: "
<< displayWord << endl;
dashReplaced = 'N';
} //end if
}
else //processed when dashReplaced contains 'N'
{
//add 1 to the number of incorrect guesses
numIncorrect += 1;
//if the number of incorrect guesses is 10,
//the game is over
if (numIncorrect == 10)
{
gameOver = 'Y';
cout << endl << "Sorry, the word is "
<< origWord << endl;
} //end if
} //end if
} //end while
system("pause");
return 0;
} //end of main function
My only edit to the program is directly under the header of Entry Storage and Error Message. I have tried a single for loop, but that simply displayed the error message for every letter entered. Not only that but it displayed it 26 times. Adding a Break command fixed that and it only displayed once. However, it still displayed on every entry.
A member of Cplusplus, pointed out that I was incorrectly testing the same variable against the array in the same location. That is why it displayed the error on every entry. Now with this loop, the error only displays when an entry is entered twice. However, the error message displays all 26 times once more. On top of that, it will only error if the letters are entered one after another.
For example, if I enter A then X then A again, no error is shown. If I enter, A then A again, the error is displayed 26 times. Something is clearly wrong with how the letter variable is being entered into the array on top of the whatever is causing the error message to display multiple times.
Any amount of assistance would be greatly appreciated.
Edit: My professor has gotten back to me and suggested using the following instead of what I have been tinkering with:
for (int x=0; x<5; x++)
if (origWord[x] == letterEntered)
origWord[x] = '-';
Is it just me, or does this miss the mark completely? I haven't tried converting it into my program as a simple copy and paste job produces compile errors. However, I don't see how that does anything with what I'm trying to do.
This set's all entries of your letterGuess array to the most recently guessed letter.
letterGuess[x] = letter;
This isn't what you want.
You need to think about the actual algorithm you need to implement:
The user enters a guess
Check to see if they've already guessed that letter
If they have, display an error message, return to 1.
If they have not, save that guess, continue with the game logic.
If you have already learned about standard containers, this can be trivially done with a std::set, or a std::vector that has been sorted.
You need to compare each element in the array to the guessed word. Best use a for loop for this. No more needs to be said if this is an assignment.
Also don't use system("cls") in your program, it is a massive security flaw and may lose you marks.
hi im trying to do a while loop, im new to programming and reading online i cant really get my head around it, i have used flag to show that the inputted name matches the name in the data file, i want to do this so that after i know it doesnt match it loops it the whole thing again, i have no clue how to implement this,
{
clrscr();
cout << "This Is The Option To Delete A Record\n";
char yesno;
char search;
char name[21];
int flag = 0;
cout << "Enter Employee Name : ";
Input(name,20);
for (int r=0;r<row;r++)
{
if( strnicmp(name, emp[r].first_name, strlen(name) ) == 0 )
{
flag = 1;
clrscr();
cout << "Employee Number - " << emp[r].employee_number << endl;
cout << "Name - " << emp[r].first_name << " " << emp[r].surname << endl;
cout << "Department Number - " << emp[r].department_number << endl;
cout << "Week Ending Date - " << emp[r].weekend << endl;
cout << "Delete This Record (Y/N)? : ";
Input(yesno);
yesno = tolower(yesno);
if ( yesno == 'y' )
{
emp[r].deleted = true;
cout << "Record Has Been Deleted";
}
else if ( yesno == 'n')
{
cout << "Record Hasn't Been Deleted";
}
}
}
if (flag == 0)
{
cout << "There Are No Matching Records" << endl;
}
pressKey();
}
It's pretty simple, so have a bunch of code you want to keep executing it while a flag is zero, so that's just
int flag = 0;
while (flag == 0)
{
// whole bunch of code
}
That's it, just replace 'whole bunch of code' with the code you've written above.
Implementing this in a while loop would look like this:
bool flag=false;
while(!flag){
...
if(<find a match>) flag=true;
}
Assuming you understand the for loop, I think you can understand the while loop quite easily based on the comparison of for and while.
See, you used a for loop:
for (int r=0;r<row;r++){
// do stuff
}
There are 3 key points here.
int r=0 This is your initial condition.
r<row This is your condition which keeps the loop running.
r++ This is what happens at the end of each iteration of loop.
To rephrase the statements above:
Considering r equals zero initially, while r is less than row, increment r.
Now we can easily see how while loop is striking us:) To implement this, consider the following while loop example:
int r=0; //(1)
while(r<row){ //(2)
//do stuff
r++; //(3)
}
See, now the 2 loops do practically the same thing.
If you want to do operations based on a flag, you can also prefer an infinite loop:
while(1==1){
if(some condition)
break;
}
as well as an infinite for loop:
for(;;){
if(if some condition)
break;
}
Again, 2 loops are practically the same.
so basically, you have a file with some data. And also, you accept some data from the user.
And then you perform a comparison between the appropriate fields of the two sets.
Why would you want to do it all over again once the entire comparison (file process) is done?
if you simply want to run an infinite loop, you can do this:
while(true)
{
//your code
}
you can do same with a for loop also. infact for loop and while loop both are same except for the syntax. i.e. an infinite for loop.
for (int r=0;r<row;r++)
{
if(r==row-1)
{
r=0;
}
}
I guess what you want to do is to, once one set of user input doesn't match the file content, you want to take another set and match it again and so on.
so you don't need an infinite or always executing loop for this.
Just make your comparison module a separate function which should accept the set of user inputs. All you do is accept user inputs and show the result. And give the user an option to re-enter inputs.
Below is simple algo for what you want.
int main()
{
char a='a';
while(a != '~')
{
TakeUserInput();
if(PerformComparison())
{
cout << "Success";
break;
}
}
}
inside TakeUserInput() you do all those cin << to set a global array or set of global variable. also, you cin << a, to terminate program at your will.
and inside PerformComparison(), you do what you have posted here in your question.
So i'm currently doing the exercices in my programming book "Programming: Principles and practice using c++" from Bjarne Stroustrup and i'm curently stuck at one exercice. Basically, the exercice is to write a program that bleeps out words it doesn't like. The way it works is that the user inputs a string and the program repeats the word. If the word the user enters is part of the dislike vector, the word is replaced by "Bleep". (I don't know if I explained this right, but it shouldn't be to complicated to understand).
This is my version of the program:
int main()
{
string dislike = "Potato";
string words = " ";
cout << "Please enter some words: " << endl;
while(cin>>words)
{
if(words==dislike)
{
cout << "Bleep!" << endl;
}
else
{
cout << words << endl;
}
}
system("pause");
return 0;
}
As you can see, this version isn't using vectors (and it should, because the exercice is right after the explanation of vectors in the chapter). So my question is, how can I implement a vector with many "dislike" words in it like this:
vector<string>dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
and make it so it works like my other version without vectors (repeats words, but bleeps the dislike words). I can't seem to understand how to navigate in a vector so that it only bleeps the "dislike" words.
If someone could give me a hand and explain to me how it works (please do not just give me the answer) it would be very appreciated.
Thank you for your time and help, learning c++ alone isn't always simple, and I thank this website for making my learning curve a bit easier.
bobicool
Ok, let me explain a simple approach to it. There are more elegant ones, but for now it's important that you get a feeling of how std::vector can be accessed and how to compose control structures correctly.
Step 1 - looping through all elements of a vector
You can use iterators to go through all elements of a vector.
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
// now *it gives access to the current element (here: current dislike word)
if (*it == words) {
// ... yeah, we found out the current word is on the list!
}
}
You get an iterator to the first element in a vector by calling begin(), then keep incrementing (++it) it until you reached the end of the vector. I use const_iterator here because I'm not going to modify any elements, if you need to, use iterator.
with a std::vector, indexing via [index] is also possible (but not recommended, usually):
for(size_t i = 0;i < dislike.size(); ++i) {
// dislike[i] is the current element
if (dislike[i] == words) {
// huuuuray! another BEEEP candidate
}
}
Step 2 - break the loop early
As soon as you know what for sure that we have a dislike word, you don't need to search the vector further.
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
if (*it == words) {
// we found a positive match, so beep and get out of here
cout << "Bleep!" << endl;
break;
}
}
Step 3 - make a note if we handled a word already
bool is_beep = false;
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
if (*it == words) {
// we found a positive match, so beep and get out of here
cout << "Bleep!" << endl;
is_beep = true;
break;
}
}
// this is not a dislike word if is_beep is false, so print it as usual
if (!is_beep) {
cout << words << endl;
}
Step 4 - putting it all together
int main()
{
vector<string>dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
string words = " ";
cout << "Please enter some words: " << endl;
while(cin>>words)
{
bool is_beep = false;
for(vector<string>::const_iterator it = dislike.begin(); it != dislike.end(); ++it) {
if (*it == words) {
// we found a positive match, so beep and get out of here
cout << "Bleep!" << endl;
is_beep = true;
break;
}
}
// this is not a dislike word if is_beep is false, so print it as usual
if (!is_beep) {
cout << words << endl;
}
}
system("pause");
return 0;
}
Check out std::find for a more idiomatic solution - it basically saves you the inner loop. You can also get rid of that bool in the last code sample if you re-structure a bit. I'll leave that as an exercise to you (hint: keep the iterator alive and check out its value after terminating the loop).
int main()
{
vector<string> dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
string words;
cout << "Please enter some words: " << endl;
while(cin >> words)
{
if(find(dislike.begin(), dislike.end(), words) != dislike.end())
{
cout << "Bleep!" << endl;
}
else
{
cout << words << endl;
}
}
system("pause");
return 0;
}
For std::find add #include <algorithm> to your source.
use std::find(your_vector.begin(), your_vector.end(), words)
int main()
{
vector<string>dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
string words = " ";
cout << "Please enter some words: " << endl;
while(cin>>words)
{
if(std::find(dislike.begin(), dislike.end(), words) != dislike.end())
{
cout << "Bleep!" << endl;
}
else
{
cout << words << endl;
}
}
system("pause");
return 0;
}
Here is my solution to that particular question in the book when i was reading it. :) hope it's self-explanatory.
/*THE QUESTION GOES LIKE;
Write a program that “bleeps” out words that you don’t like; that is, you read in words
using cin and print them again on cout. If a word is among a few you have defined, you
write out BLEEP instead of that word. Start with one “disliked word” such as string
disliked = “Broccoli”;
When that works, add a few more.*/
#include "std_lib_facilities.h" // this is a standard library header that came with
the book
int main () {
vector<string> dislike = {"Dislike", "Alike", "Hello", "Water"}; /* defining a vector
for the disliked words. */
vector<string> words; //initializing vector for the read words.
cout << "Please enter some words\n"; //prompt user to enter some words.
for( string word; cin >> word;) //this current word typed is read in.
words.push_back(word); // word read in are pushed into the vector "words".
sort(words); /* function for the standard library for sorting data...this makes the data from the vector "words" appears in alphabetical order. */
for (int i=0; i<words.size(); ++i){ /*this acts as an iterator. and goes through all the element of the vector "words". */
if(i==0 || words[i-1]!=words[i]){ /*this prevents the words from repeating....just an option incase the user enters same kinda words twice or more. */
if(words[i]!=dislike[0] && words[i]!=dislike[1] && words[i]!=dislike[2] && words[i]!=dislike[3]) /*This test checks whether the words typed match any of the elements of the vector "dislike".if they don't match; */
cout << words[i]<< '\n'; //prints out the words.
else
cout << "BlEEP!\n"; //if they match....print out "BlEEP!".
}
}
}
I am learning C++. This Program has been changed some.
Write a program that "bleeps" out bad words that you don't like; that is,
you read in words using cin and print them again on cout. If a word is among a few you have defined, you write out BLEEP and or have it to BLEEP(Sound) instead of that word. Start with one "bad word" such as -- string badword = "arse"; When that works, add a few more or write a whole program based on all the bad words that you do not want printed out.
while (cin >> words)
{
if(find(badwords.begin(), badwords.end(),words) !=badwords.end())
{
cout << " " << endl; // You can put Bleep in or leave it out (Blank) if blank
// it will leave a blank in the phrase when it prints
Beep(523,500); // This is to Bleep (Sound) when a bad word is found
cin.get();
}
else
{
cout << words << endl;
}
}
Since someone gave the answer I have Changed the program some. That is for you to learn.
This runs on Visual Studio Express 2012
I have solved this problem using the ideas that have already been learned in the previous chapters, not going beyond what you understand.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<string> disliked;
//adding disliked words to the vector
disliked.push_back("dog");
disliked.push_back("cat");
disliked.push_back("goat");
disliked.push_back("cow");
disliked.push_back("sheep");
disliked.push_back("pig");
string words=""; //this variable will store the input from the user.
while(cin>>words)
{//test every entered word to see if it's equal to any word listed in disliked words.
if(words==disliked[0] ||//or
words==disliked[1] ||//or
words==disliked[2] ||//or
words==disliked[3] ||//or
words==disliked[4] ||//or
words==disliked[5]){
cout<<"Bleeps";}
else{
cout<<words;}
}
return 0;
//Not that I have not gone beyond what has been covered in the previous chapters.
//I know their are beautiful solutions to this problem.
//Keep learning you will know everything.
}
This question was asked a long, long time ago so the author is probably professional at this point lol, but here is simpler yet working solution for anybody who is looking for the same answer. I am learning from the beginning through Bjarne book so im not yet "affected" with higher knowledge to confuse you with but with solutions that are good enough to work based on how far we are in the book. :)
// program that bleeps out words we dont like
vector <string> words;
vector <string> bwords = {"this", "that", "then"}; //bleeped words
string sword; // temporary word
cout << "Enter few words: ";
for (string tword; cin >> tword;) // read in words
words.push_back(tword);
//check if they match beeped words
cout << "\n\nWords:\n";
for (int i = 0; i < words.size(); i++) //take word[i] from the vector
{
sword = words[i]; // temporary variable is now word[i]
for (int j = 0; j < bwords.size(); j++) // take beeped word[j] from saved words
{
if (words[i] == bwords[j]) // is word[i] same as bleeped word[j]
sword = "BLEEP"; // if word[i] is same then replace sword with BEEP
}
cout << sword << "\n"; // now we checked first word and if it matches with any of the bleeped words then it will cout bleep, otherwise it will cout first word.
}
Now in this example you can add many new bleeped words and you wont need to change the code.
This is not the best solution in "real life" programming, but at this point in the book we learned for, if, vector(not a lot of it), cout, cin.. etc so anything else just looks confusing..until this point we dont know yet about using :: , begin, true/fals, cin.get or anything like that.
//Josef.L
//2019/7/11
int main(void){
vector <string> inpute;
for(string pat; cin >>pat;){
inpute.push_back(pat);
}
for(int i=0; i < inpute.size(); i++){
if("work"== inpute[i]){
cout<<"bleep! "<<endl;}
else if("life" == inpute[i]){
cout<<"bleep! "<<endl;
}
else if("broccoli" == inpute[i]){
cout<<"bleep! "<<endl;
}
else if("homework" == inpute[i]){
cout<<"bleep! "<<endl;
}
else{
cout <<inpute[i]<<endl;
}
}
return 0;}
//However, the entire source code is too long and boring, so there should be an improvement.
That's my solution, where you can add as many words as you want without changing the code.
#include "std_lib_facilities.h"
int main()
{
vector<string> dislike;
dislike.push_back("Potatoes");
dislike.push_back("Peanuts");
dislike.push_back("Coconut");
vector<string> words;
for (string temp_word; cin >> temp_word; )
{
for (int i = 0; i < dislike.size(); ++i)
{
if (temp_word == dislike[i])
{
words.push_back("BLEEP");
break;
}
else if (i == dislike.size() - 1 && temp_word != dislike[dislike.size() - 1])
{
words.push_back(temp_word);
break;
}
}
}
for (string temp_word : words)
{
cout << temp_word << ' ';
}
keep_window_open();
}
“Simple can be harder than complex: You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains.” ― Steve Jobs
#include "std_lib_facilities.h"
int main()
{
vector<string>disliked;
disliked.push_back("Apple");
disliked.push_back("OliveOil");
disliked.push_back("Strawberry");
disliked.push_back("Lemon");
cout<<"Please type some words:"<<"\n";
string words=" ";
while(cin>>words)
{
if (words==disliked[0] | words==disliked[1]|
words==disliked[2] | words==disliked[3])
{cout<<"BLEEP"<<"\n";}
else{cout<<words<<"\n";}
}
keep_window_open();
}