char* szWords[] = { "caralho", "porra" };
if (IsGoldGrade(pObj)) //Ignore, its ok. //Crashing after i added the
{
for (int x = 0; x < sizeof(szWords); x++) {
if (strstr((strlwr((char*)szWords[x])), szChat)) {
char szBuffer[256];
sprintf(szBuffer, "You can't type %s", szWords[x]);
Announce(pObj, szBuffer);
memset(szBuffer, 0, 256);
return;
}
}
}
Idk but I can't use this as "code" on stackoverflow.
Pastebin: http://pastebin.com/u8yit8Rw
PS: I can't use StrStrI because im using Visual Studio 2003.
Your for loop condition is wrong. You want to iterate the array of pointers to char.
Your loop for (int x = 0; x < sizeof(szWords); x++) continues while x < sizeof(szWords). But sizeof(szWords) is not array length. It just says how many bytes your array occupies in memory. It is system dependant, however it is twice the size of pointer to char, so probably 8 or 16 bytes. You need to divide this size by size of the array element then you will get the proper array size.
Rewrite your for loop like this:
for (int x = 0; x < sizeof(szWords)/sizeof(szWords[0]); x++)
or if your compiler supports C++11 you can try range-based for:
for (const char *word : szWords)
Apart from that, if you are writing C++ code you really should use STL and other C++ features. For instance your array of strings should be declared as:
std::vector<std::string> words = { "caralho", "porra" };
or if your compiler doesnt support C++11 (then really change it...)
std::vector<std::string> words;
words.push_back("caralho");
words.push_back("porra");
for (std::size_t i = 0; i < words.size(); ++i) {
// since you are using C string functions you will need word as C string
const char *word = words[i].c_str();
// do whatever you want with word
}
Also consider reading modern C++ book before writing code.
From the look of it, this is a function which checks if the user has written a prohibited word?
I'd replace char* szWords[]... with std::vector<std::string> to store the prohibited words, and use std::find to see if the input is in that list.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> bannedWords{"hamster", "elderberries", "etcetera"};
bool isBanned(const std::string &str) {
return std::find(bannedWords.begin(), bannedWords.end(), str) != bannedWords.end();
}
int main() {
std::cout << "Is 'wally' banned? " << isBanned("wally") << std::endl;
std::cout << "Is 'elderberries' banned? " << isBanned("elderberries") << std::endl;
}
More information about std::find is here.
Here's an online demo
Related
I'm getting this error hence I am new to c++ I could not understand
please help me!!!
I am writing a palindrome code
This is the code given below:.............
I am basically here using some extra concepts not doing in-direct fashion.
if anyone can post the correct code he/she is most welcome...
//palindrome
#include <cstring> //or use #include <string.h>
#include <iostream>
using namespace std;
void Palindrom(string& );
void Palindrome(string& word)// same as (const string& word)
{
int n = word.length();
string word2;
char reverse[n];
for(int i = 0; i <=n; i++){
word[i]=tolower(word[i]);
}
word2=word; //now both are small
for(int i = n-1; i >=0; i--){
reverse[n-1-i]=word2[i];
cout<<reverse[n-1-i];
}
for(int i =0; i >n; i++){ //printing reversed
cout<< " Reverse: "<<reverse[i]<<endl;
}
// word is ok and word2 gets reversed
for (int i = 0; i <= n; i++){
if(word[i]==reverse[i])
{
cout<<"\nit is palandrome ";
}
cout<<"\nit is not a palindrome ";
}
}
int main()
{ string k="YuUuy";
void Palindrome(k);
return 0;
}
Correct syntax for calling a function is Palindrome(k); without the void.
Few remarks:
Get a good c++
book.
// same as (const string& word) is not true.
You did not include <string> header.
It's good practice to use std::size_t for indices, but beware of unsigned>=0 condition being always true.
char reverse[n]; is wrong, n must be a compile-time constant, VLA are not part of the C++ standard.
Function calls should not have return type. Change void Palindrome(k); in main() function to Palindrome(k);
While declaring array, the expression should have constant value. So you can't use char reverse[n];. Change it to char *reverse = new char[n]; and deallocate it using delete[] reverse; after you are done using it.
I would recommend you to use smart pointer. You should also take a look at std::string instead of using stream of char.
I am faced with a simple yet complex challenge today.
In my program, I wish to insert a - character every three characters of a string. How would this be accomplished? Thank you for your help.
#include <iostream>
int main()
{
std::string s = "thisisateststring";
// Desired output: thi-sis-ate-sts-tri-ng
std::cout << s << std::endl;
return 0;
}
There is no need to "build a new string".
Loop a position iteration, starting at 3, incrementing by 4 with each pass, inserting a - at the position indicated. Stop when the next insertion point would breach the string (which has been growing by one with each pass, thus the need for the 4 slot skip):
#include <iostream>
#include <string>
int main()
{
std::string s = "thisisateststring";
for (std::string::size_type i=3; i<s.size(); i+=4)
s.insert(i, 1, '-');
// Desired output: thi-sis-ate-sts-tri-ng
std::cout << s << std::endl;
return 0;
}
Output
thi-sis-ate-sts-tri-ng
just take an empty string and append "-" at every count divisible by 3
#include <iostream>
int main()
{
std::string s = "thisisateststring";
std::string res="";
int count=0;
for(int i=0;i<s.length();i++){
count++;
res+=s[i];
if(count%3==0){
res+="-";
}
}
std::cout << res << std::endl;
return 0;
}
output
thi-sis-ate-sts-tri-ng
A general (and efficient) approach is to build a new string by iterating character-by-character over the existing one, making any desired changes as you go. In this case, every third character you can insert a hyphen:
std::string result;
result.reserve(s.size() + s.size() / 3);
for (size_t i = 0; i != s.size(); ++i) {
if (i != 0 && i % 3 == 0)
result.push_back('-');
result.push_back(s[i]);
}
Simple. Iterate the string and build a new one
Copy each character from the old string to the new one and every time you've copied 3 characters add an extra '-' to the end of the new string and restart your count of copied characters.
Like 99% problems with text, this one can be solved with a regular expression one-liner:
std::regex_replace(input, std::regex{".{3}"}, "$&-")
However, it brings not one, but two new problems:
it is not a very performant solution
regex library is huge and bloats resulting binary
So think twice.
You could write a simple functor to add the hyphens, like this:
#include <iostream>
struct inserter
{
unsigned n = 0u;
void operator()(char c)
{
std::cout << c;
if (++n%3 == 0) std::cout << '-';
}
};
This can be passed to the standard for_each() algorithm:
#include <algorithm>
int main()
{
const std::string s = "thisisateststring";
std::for_each(s.begin(), s.end(), inserter());
std::cout << std::endl;
}
Exercise: extend this class to work with different intervals, output streams, replacement characters and string types (narrow or wide).
This question already has answers here:
Finding length of char array
(6 answers)
Closed 9 years ago.
I'm creating a text-based hangman game in Code::Blocks ( C++ Obviously ;) ).
So i've created an array char knownLetters[]; but i'll have no idea how long the word will be, how can i calculate how many char's there will be in the string?
Code:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
string GenerateWord() // Generate random word to be used.
{
srand(time(NULL));
int wordID = rand() % 21;
string wordList[20] = {"Dog" ,"Cat","Lion","Ant","Cheetah","Alpaca","Dinosaur","Anteater","Shark","Fish","Worm","Lizard","Bee","Bird","Giraffe","Deer","Crocodile","Wife","Alligator","Yeti"};
string word = wordList[wordID];
return word;
}
void PrintLetters() // Display the word including underscores
{
string word = "";
char knownLetters[word];
for(int pos = 0; pos < word.length(); pos++) {
if(knownLetters[pos] == word[pos]) cout << word[pos];
else cout << "_";
}
cout << "\n";
}
void PrintMan() // Display the Hangman to the User
{
// To Be completed
}
void PlayerLose() // Check For Player Loss
{
// To Be completed
}
void PlayerWin() // Check For Player Win
{
// To Be completed
}
int main()
{
cout << "Hello world!" << endl;
return 0;
}
Thanks in Advance!
From the random string generated you use the size method to find its size
http://www.cplusplus.com/reference/string/string/size/
This can then be used for the size of the array or better yet use a vector and then you do not need to worry about the size
void PrintLetters(const std::string& word) // Pass the word in here
{
const int size = word.size();
If it is a C char-based string, you can use strlen. However, the string must be \0-terminated.
Use a .size() method of std::string
I think Standard Template Libraries (STL) can be of great use to you here.
Specially std::vectors. Vectors does not require the length of string you want to put in.
You can use ITERATORS to navigate inside a vector.
Can find the length of the generated word through sizeof.
I.E
int length = sizeof(word);
answer from:
Finding length of char array
I'm trying to write a code which stores strings in an array. I'm trying to do it with char* but I couldn't achieve. I search the net but couldn't find an answer. I've tried the code below, but it didn't compile.I use string stream because at some point I need to concatenate a string with an integer.
stringstream asd;
asd<<"my name is"<<5;
string s = asd.str();
char *s1 = s;
> I'm trying to write a code which stores strings in an array.
Well, first you'll need an arary of strings. I don't like using naked arrays, so I use std::vector:
std::vector<std::string> myStrings;
But, I understand you have to use an array, so we'll use an array instead:
// I hope 20 is enough, but not too many.
std::string myStrings[20];
int j = 0;
> I use string stream because ...
Okay, we'll use stringstream:
std::stringstream s;
s << "Hello, Agent " << 99;
//myStrings.push_back(s.str()); // How *I* would have done it.
myStrings[j++] = s.str(); // How *you* have to do it.
That gets us one string, but you want an array of them:
for(int i = 3; i < 11; i+=2) {
s.str(""); // clear out old value
s << i << " is a" << (i==9?" very ":"n ") << "odd prime.";
//myStrings.push_back(s.str());
myStrings[j++] = s.str();
}
Now you have an array of strings.
Complete, tested program:
#include <sstream>
#include <iostream>
int main () {
// I hope 20 is enough, but not too many.
std::string myStrings[20];
int j = 0;
std::stringstream s;
s << "Hello, Agent " << 99;
//myStrings.push_back(s.str()); // How *I* would have done it.
myStrings[j++] = s.str(); // How *you* have to do it.
for(int i = 3; i < 11; i+=2) {
s.str(""); // clear out old value
s << i << " is a" << (i==9?" very ":"n ") << "odd prime.";
//myStrings.push_back(s.str());
myStrings[j++] = s.str();
}
// Now we have an array of strings, what to do with them?
// Let's print them.
for(j = 0; j < 5; j++) {
std::cout << myStrings[j] << "\n";
}
}
How about something like this?
vector<string> string_array;
stringstream asd;
asd<<"my name is"<<5;
string_array.push_back(asd.str());
char *s1 = s;
Is illegal. You either need:
const char *s1 = s.c_str();
if you're not set on char*, or you'll need to allocate a new char* and use strcpy to copy the contents from the string.
Just change your code to
char const* s1 = s.c_str();
because a pointer to char can't store a string object, only a pointer to char, which is what c_str() returns.
I wouldn't use the char * directly. I would wrap it in something like the template below. You can override the operators you need to do any more operations (example, I would make data a private member, and override the operators to make the data print out cleanly). I did the assignment operator just to demonstrate how clean that could make code.
#include "MainWindow.h"
#include <stdio.h>
using namespace std;
template<size_t size>
class SaferChar
{
public:
SaferChar & operator=(string const & other)
{
strncpy(data, other.c_str(), size);
return *this;
}
char data[size];
};
int main(int argc, char *argv[])
{
SaferChar<10> safeChar;
std::string String("Testing");
safeChar = String.c_str();
printf("%s\n", safeChar.data);
return 0;
}
I am working on ROT13 for c++ practice. however this bit of code here returns an error and fails to compile, i do not understand why! I am posting a snippet of code in the following lines
string encode(string &x)
{
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
for (size_t l=0;l<x.size();++l){
cout<<x[l];
cout<< strchr(alphabet,x[l]);
}
return x;
}
Q2. Also help me return the index of the matching letter from alphabet[] (e.g.,5 for 'f') to which i can add 13 and append that to x and so on ..
Q3. Besides practice, which course in CS would help me develop more efficient algorithms? Is it theory of computation, discrete mathematics, or algorithms ?
In order, starting with question 1:
The following compiles fine for me:
#include <iostream>
#include <cstring>
std::string encode(std::string &x)
{
char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
char *ptr;
for (size_t l=0;l<x.size();++l){
std::cout<<x[l];
std::cout<< std::strchr(alphabet,x[l]);
}
return x;
}
int main (int argc, char* argv []) {
return 0;
}
Make sure:
you include the headers given, for cout and strchr.
use std:: prefixes unless you're using the std namespace.
fix that ptr problem.
Question 2:
If you're looking for a handy ROT-13 method, consider using two C strings, one for the source and one for the translation:
char from[] = "abcdefghijklmnopqrstuvwxyz";
char to [] = "nopqrstuvwxyzabcdefghijklm";
Then you can use strchr to look it up in the first one and use that pointer to find the equivalent in the second.
char src = 'j';
char *p = strchr (from, src);
if (p == NULL)
std::cout << src;
else
std::cout << to[p - from];
That would output the character as-is if it wasn't found or look up the translation if it was found. You may also want to put the capital letters in there as well.
Question 3:
If you want to learn about efficient algorithms, I'd go for, surprisingly enough, an algorithms course :-)
Theory of computation sounds a little dry, though it may well cover the theoretical basis behind algorithms. Discrete mathematics has applicability to algorithms but, again, it's probably very theoretical. That's all based on what the words mean, of course, the actual subject areas covered may be totally different, so you should probably take it up with the people offering the courses.
Extra bit:
If you're looking for something to compare your own work to, here's one I put together based on my suggestions above:
#include <iostream>
#include <cstring>
std::string rot13 (std::string x)
{
char from[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
char to [] = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM";
std::string retstr = "";
for (size_t i = 0; i < x.size(); ++i) {
char *p = std::strchr (from, x[i]);
if (p == 0)
retstr += x[i];
else
retstr += to[p - from];
}
return retstr;
}
int main (int argc, char* argv []) {
std::string one = "This string contains 47 and 53.";
std::string two = rot13 (one);
std::string three = rot13 (two);
std::cout << one << '\n';
std::cout << two << '\n';
std::cout << three << '\n';
return 0;
}
The building of the return string could have probably been done more efficiently (such as a new'ed character array which becomes a string only at the end) but it illustrates the "lookup" part of the method well.
The output is:
This string contains 47 and 53.
Guvf fgevat pbagnvaf 47 naq 53.
This string contains 47 and 53.
which you can verify here, if necessary.
Cast alphabet to a const char*, it should work afterwards. Keep in mind that type[] is different from type *.