Problem with function C++
Hello
I am writing code for a program that blocks words that I don't like in my program.
For example, if I write "Oh hello there broccoli", where "broccoli" is the word that i don't like, the program will write "Oh hello there bobba"
The problem is that always writes "bobba".
INPUT: how are you broccoli?
OUTPUT: bobba bobba bobba bobba
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
|
#include "stdafx.h"
#include "iostream"
#include "vector"
#include "string"
using namespace std;
bool test(string);
int main()
{
vector <string> words;
for (string current_word; cin >> current_word;)
words.push_back(current_word);
for (int i = 0; i < words.size(); ++i)
{
if (i == 0 || words[i - 1] != words[i])
{
if (test(words[i]))
cout << words[i] << '\t';
else
cout << "\abobba" << '\t';
}
}
cout << "\n\n";
system("pause");
return 0;
}
bool test(string words)
{
string blocked [3] = { "shit", "bitch", "fuck" };
for (int i = 0; i < sizeof(blocked); i++)
{
if (blocked[i] == words)
return false;
}
return true;
}
|
sizeof(blocked)
doesn't mean what you think it means.
1 2 3 4 5 6 7 8 9 10
|
template <typename T, size_t N>
constexpr size_t array_length(const T (&)[N]){
return N;
}
bool test(string words)
{
static const string blocked[] = { "shit", "bitch", "fuck" };
for (int i = 0; i < array_length(blocked); i++)
//...
|
Why soo complicated, much easier if you use modern C++.
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
|
#include "iostream"
#include "vector"
#include "string"
using namespace std;
bool test(const string& word);
int main()
{
vector <string> words;
for (string current_word; cin >> current_word;)
words.push_back(current_word);
for (const string& s: words)
{
if (test(s))
cout << "\abobba";
else
cout << s;
cout << '\t';
}
cout << "\n\n";
system("pause");
return 0;
}
bool test(const string& word)
{
vector<string> blocked = { "shit", "bitch", "fuck", "broccoli" };
return find(blocked.begin(), blocked.end(), word) != blocked.end();
}
|
how are you broccoli
^Z
how are you bobba
|
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
|
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
#include <iterator>
#include <algorithm>
using namespace std;
const vector<string> blocked = { "shit", "bitch", "fuck", "broccoli" };
const string replacement = "\abobba";
string lower( string s )
{
for ( char &c : s ) c = tolower( c );
return s;
}
bool test( string s )
{
return find( blocked.begin(), blocked.end(), lower( s ) ) != blocked.end();
}
int main()
{
replace_copy_if( istream_iterator<string>( cin ), {}, ostream_iterator<string>( cout, " " ), test, replacement );
}
|
Topic archived. No new replies allowed.