I've been working on a program my professor gave us awhile back and I've run into a logic issue, as in I can't figure out how to exactly do this. I need to output one word on each line of a sentence input by the user. For example, the user inputs "Hello World I'm Chris" and the program needs to output:
Hello
World
I'm
Chris
This is what I have so far:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
int length;
cout << "Enter the sentence now." << endl;
getline(cin, sentence);
for(int i = 0; i < sentence.length(); i++)
{
if(sentence[i] != '\0')
{
cout << sentence[i];
}
else if(sentence[i] == '\0')
{
cout << endl;
}
}
system("pause");
}
However, when I run it, the program basically just outputs the same sentence. Is there another way I can do this? Many thanks.
According to this the \0 does not represent a whitespace. It seems you want something more like:
[...]
if(sentence[i] == ' ') cout << endl; // check for whitespace
else cout << sentence[i];
[...]
By the way, due to the way markdown formats text, the 'one word per line' thing was not clear, I had to fake-edit your post to see what exactly you meant. I think using a code tag would solve that.
Ok first of all with the code feel free to add in the input stuff you have in before!
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence = "Hello World";
int length;
string temp = "";
for(int i = 0; i < sentence.length(); i++)
{
temp += sentence[i];
if(sentence[i] == ' ')
{
cout << temp << "\n";
temp = "";
}
}
std::cout << temp;
return 0; //*
}
Your orignal code does the following logic. If it not the end of the file output the current character. Which it does so make sure you add in \n to the end of every word (Just to make debugging easier for you! You can always fix that later)
The logic of the above code does this. Create a temp variable that we will just keep adding letters to until we find a space character. When we find a space character output the temp variable. And reset it do this until the end of the sentence then at the end of the program output temp again since we hit the end of line character!
Your program outputs the same sentence because you told it to.
for(int i = 0; i < sentence.length(); i++)
{
if(sentence[i] != '\0') // If the current char is not the end,
{
cout << sentence[i]; // print the character.
}
else if(sentence[i] = '\0') // This should be "=="
{
cout << endl;
}
}
Basically, you are printing each letter in the sentence back to std::cout.
Please search StackOverflow for "C++ print word sentence", as many people have posted questions about this assignment.
Edit 1: The fundamentals of the assignment
The assignment requires you to extract letters from the input string to form a word. There are many ways to do this. Search your text book or reference manual for the std::basic_string class and see what functions could help you.
Some people start from the first letter in the sentence and search for the next character that is not a letter:
const char valid_letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
sentence.find_first_not_of(valid_letters);
And they use the returned position to get a substring (std::string::substr) between the two positions.
Another approach is to use a loop. If the present character is a letter, append to the word string.
Again search and see what examples you can find.
Related
I need to write a sentence in Pig Latin form and I am almost done it successfuly except for 1 case and I almost give up
for example :
If my word starts at a\e\o\u\i the word will look like easy -> easyway , apple -> appleway
and if it doesnt start with a letter that I wrote above
it will look like that: box -> oxbay , king -> ingkay
I succeed with the bolded part but in the first part with a\e\o\u\i letter at the beginning , I dont know where to put the w before and need some help with it
This is my code , thanks in advance
#include <iostream>
//Since those are used in ALL function of program, it wont hurt to set it to global
//Else it is considered EVIL to declare global variables
const int maxLine = 100;
char phraseLine[maxLine] = { '\0' };
void pigLatinString();
using namespace std;
void main()
{
// Displayed heading of program
cout << "* You will be prompted to enter a string of *" << endl;
cout << "* words. The string will be converted into *" << endl;
cout << "* Pig Latin and the results displayed. *" << endl;
cout << "* Enter as many strings as you would like. *" << endl;
//prompt the user for a group of words or press enter to quit
cout << "Please enter a word or group of words. (Press enter to quit)\n";
cin.getline(phraseLine, 100, '\n');
cout << endl;
// This is the main loop. Continue executing until the user hits 'enter' to quit.
while (phraseLine[0] != '\0')
{
// Display the word (s) entered by the user
cout << "You entered the following: " << phraseLine << endl;
// Display the word (s) in Pig Latin
cout << "The same phrase in Pig latin is: ";
pigLatinString();
cout << endl;
//prompt the user for a group of words or press enter to quit
cout << "Please enter a word or group of words. (Press enter to quit)\n";
cin.getline(phraseLine, 100, '\n');
}
return;
}
void pigLatinString() //phraseLine is a cstring for the word, maxline is max length of line
{ //variable declarations
char tempConsonant[10];
tempConsonant[0] = '\0';
int numberOfConsonants = 0;
char previousCharacter = ' ';
char currentCharacter = ' ';
bool isInWord = 0;
// for loop checking each index to the end of whatever is typed in
for (int i = 0; i < maxLine; i++)
{
//checking for the end of the phraseline
if (phraseLine[i] == '\0')
{//checking to see if it's in the word
if (isInWord)
{//checking to see that there wasn't a space ahead of the word and then sending the cstring + ay to the console
if (previousCharacter != ' ')
cout << tempConsonant << "ay" << endl;
}
return;
}
// this covers the end of the word condition
if (isInWord)
{// covers the condition of index [i] being the space at the end of the word
if (phraseLine[i] == ' ')
{
// spits out pig latin word, gets you out of the word, flushes the temp consonants array and resets the # of consonants to 0
cout << tempConsonant << "ay";
isInWord = 0;
tempConsonant[0] = '\0';
numberOfConsonants = 0;
}
cout << phraseLine[i] ;
}
else
{//this covers for the first vowel that makes the switch
if (phraseLine[i] != ' ')
{// sets the c string to what is in the phraseline at the time and makes it capitalized
char currentCharacter = phraseLine[i];
currentCharacter = toupper(currentCharacter);
// this takes care of the condition that currentCharacter is not a vowel
if ((currentCharacter != 'A') && (currentCharacter != 'E') &&
(currentCharacter != 'I') && (currentCharacter != 'O') && (currentCharacter != 'U'))
//this sets the array to temporarily hold the consonants for display before the 'ay'
{//this sets the null operator at the end of the c string and looks for the next consonant
tempConsonant[numberOfConsonants] = phraseLine[i];
tempConsonant[numberOfConsonants + 1] = '\0';
numberOfConsonants++;
}
else
{// this sets the boolean isInWord to true and displays the phraseline
isInWord = 1;
cout << phraseLine[i];
}
}
else
{
cout << phraseLine[i] ;
}
}
previousCharacter = phraseLine[i];
}
return;
}
You have two conditions to consider. if your word starts with a vowel, just add "way" to the end of the word, else move the first letter and add "ay" to the end.
This is a task that can be made a lot simpler by using std::string instead of C-strings. This is because you are now no longer concerned with exceeding your length or losing the null character. It also allows easier access to the Standard Library algorithms.
#include <algorithm>
#include <iostream>
#include <string>
std::string make_pig_latin(const std::string& word) {
std::string vowels("aeiou");
std::string newWord(word);
if (newWord.find_first_not_of(vowels) == 0) {
// Word starts with a consanant
std::rotate(newWord.begin(), newWord.begin() + 1, newWord.end());
newWord += "ay";
} else {
newWord += "way";
}
return newWord;
}
int main() {
std::cout << make_pig_latin("apple") << '\n'
<< make_pig_latin("box") << '\n'
<< make_pig_latin("king") << '\n'
<< make_pig_latin("easy") << '\n';
}
The function above highlights how you can go about structuring your conversion. You just need to know if your word starts with a vowel or not, and take the appropriate action.
Output:
appleway
oxbay
ingkay
easyway
I did not get the impression that you have to care about words like 'phone'.
Looking through your code, you should try to do a better job at separating your concerns. Pig Latin is easier done one word at a time, but you have string splitting code and a lot of "not Pig Latin" code in your Pig Latin function. Your main can handle getting input. You should probably have a separate function to break the line up into individual words, using std::vector to hold the words would be best since it can grow on demand and doesn't have to know a specific capacity up front. You then iterate through your array of words and translate them individually. Depending on what your actual requirements are, it's possible that you don't even have to store the translated words, just print them directly to the screen.
Here's the same program, but now it can separate words. Note how the pig latin function doesn't have to change (much, I added upper-case vowels just because I didn't want to bothered converting words) in order for the added functionality to be added.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
std::string make_pig_latin(const std::string& word) {
std::string vowels("aeiouAEIOU");
std::string newWord(word);
if (newWord.find_first_not_of(vowels) == 0) {
// Word starts with a consanant
std::rotate(newWord.begin(), newWord.begin() + 1, newWord.end());
newWord += "ay";
} else {
newWord += "way";
}
return newWord;
}
int main() {
std::string phrase(
"A sentence where I say words like apple box easy king and ignore "
"punctuation");
std::istringstream sin(phrase);
std::vector<std::string> words(std::istream_iterator<std::string>(sin), {});
for (auto i : words) {
std::cout << make_pig_latin(i) << ' ';
}
}
Output:
Away entencesay hereway Iway aysay ordsway ikelay appleway oxbay easyway ingkay andway ignoreway unctuationpay
I'm a noob and am on chapter 4 of this c++ book and I can't answer this assignment correctly.
The code that makes sense to me but doesn't work is included down below.
Here is the assignment:
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.
Help would be greatly appreciated, I might even mail you some cookies.
int main() {
vector<string> words;
for (string temp; cin >> temp; )
words.push_back(temp);
string disliked = "broccoli";
for (int i = 0; i < words.size(); ++i)
if (words[i] == disliked || disliked=="Bleep!")
cout << words[i] << "\n";
Even if I type in several words all I get out ironically is "broccoli" and nothing else.
The reason it's only printing out "broccoli" is because of these lines here:
if (words[i] == disliked || disliked=="Bleep!")
cout << words[i] << "\n";
These lines essentially mean "if the word equals broccoli, print out that word". The second part of the check, disliked == "Bleep!", is always false (because disliked is always "broccoli"), so it doesn't play a role.
We can fix things like this:
include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> words;
for (string temp; cin >> temp;)
words.push_back(temp);
string disliked = "broccoli";
for (int i = 0; i < words.size(); ++i)
if (words[i] == disliked)
cout << "Bleep!" << '\n';
else
cout << words[i] << '\n';
}
Here, the logic is "if the word is disliked, print out "Bleep", otherwise, print out the word."
If you have any more questions, I'd be happy to answer them, and any cookies would definitely be appreciated! :)
What justin say is true. A debugger could show you exactly what happen by following line by line what happen (your program is little enough to do that).
However i will answer. Here the problem comes from the line
if (words[i] == disliked || disliked=="Bleep!")
You test if the word is the disliked one and you show it. So yes, there is only broccoli. By the way you don't exactly follow what your exercise say, since you should cout bleep when the word is disliked and cout the word if not. (according to what i understand).
Hope it helps.
I am trying to understand why my iterator code will not print the correct statement even though I am passing the correct variable through to it. I am still new to C++ and have figured that this is probably an easy fix but could anyone help ??
Ps - it works fine when I have already declared an input but when I wish for the code to accept user input it gives inaccurate results
int main(){
list<string> personWords = {"Baxter","Nao","Jane"};
list <string> actionWords ={"recognise","detect","sees","pick","eats","lifts"};
list <string> directionWords = {"left","right","forwards","backwards"};
list <string> pronounWords = {"I","you","him","her"};
list <string> objectWords = {"apple","car","bus","diamond","atom","ball"};
list <string> textureWords = {"smooth","rough","shiny"};
string userInput;
cin >> userInput;
string userInputWords[3];
int counter = 0;
for(int i = 0; i <= userInput.length(); i++){
if (userInput[i] == ' '){
counter++;}
else{
userInputWords[counter] += userInput[i];
}
}
// The above for loop counts the number of words using the
// number of spaces inbetween the words and stores them in an
// array
cout << userInputWords[0] << endl; // A check to see that correct word is being printed
list <string> ::iterator check1;
check1 = find(personWords.begin(), personWords.end(), userInputWords[0]);
// searching for all of the person words
if(check1 != personWords.end()){
cout << "Your word exists in Person Words list" << endl;
}
else{
cout << "Your word does not exist in Person Words list" << endl;
}
}
this is probably an easy fix
for(int i = 0; i <= userInput.length(); i++)
^^
It should just be
for (int i = 0; i < userInput.length(); i++)
When it is less than or equals, it adds all the characters the user typed plus one.
That's why std::find couldn't find what you were typing, because it was also grabbing whatever was right after the word (probably a \0, but don't quote me on that.)
I am trying to work on a assignment which need to input two string S & str and then deliver three results (Without using any string library):
1.Determine the number and positions of the given str in S
2.Return S with any possible occurrence of str removed
ex. if S=aababacd cdefgh ,
str=aba
The Frequency is 2, position is <0,2>
The Character Delete would be cd cdefgh
Attached code is what I have done so far, I can output the Frequency and the position, but now I have few unsolved questions and I have no idea how to implement it.
1.Once I input a string with space in there, ex. abcd efg, the code will implement it immediately, it will not consider abcd efg as one string but consider it as S=abcd and str=efg , with this problem I cant input a string with blank space to test.
2.How can I output the position like this form: <0,2> , because I am using a loop to output the result so it cant not be like that, I was thinking whether I can create an array to store i and then cout it, but I failed.
3.About the character Delete problem, I found one similar problem, it said if I know how to use strcpy without using library then I would know, but I learned it and I still dont know how to handle this question, I know I can compare these two strings but I dont know how to output S without the str part.I was thinking to change the S into '\0' after loop and output it, but that was totally wrong.
I would be really appreciated if anyone could give me some advice, thank you!
#include <iostream>
#include <algorithm>
using namespace std;
void CharacterDelete(){
char S[100], str[100];
bool match =true;
cout << "Enter string S :";
cin >> S;
cout << "Enter string str :";
cin>>str;
for(int i=0; S[i]!='\0'; i++)
{
for(int j=0; str[j]!='\0';j++){
if(S[i+j]!=str[j]){
match=false;
break;
}
if(match){
S[i+j]='\0';
}
}
}
cout<<S;//Apparently thats a wrong solution
}
void Frequency(){
string S,str;
cout<<"Please input string S"<<endl;
cin>>S;
cout<<"Please input string str"<<endl;
cin>>str;
int sum=0;
for (int i=0; i<S.size(); i++)
{
if (i + str.size() > S.size()) break;
bool match=true;
for (int j=0; j<str.size(); j++)
if (S[i+j] != str[j])
{
match=false;
break;
//Once we print blank space and it would implement it immediately?
}
if(match)
{
sum++;
cout<<"Start from"<<i<<endl;
//What if we use an array to store it and then output it?but how to write it?
}
}
cout<<"The Frequency is "<<sum<<endl;
if(sum==0){
cout<<"There is no starting point"<<endl;
}
}
int main() {
Frequency();
CharacterDelete();
return 0;
}
You are using local variables S and str. You need to use S and str in main function. Then transfer this variables from main in Frequency() and CharacterDelete.
Delete characters: create new variable then copy there characters without delete-characters.
Output:
cout << "<" << num_word << ", " << number << ">\n";
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();
}