checking for character pair in array - c++

I have a character array that produces a random array of lowercase letters in the length that the user inputs. my problem is that after the array of random letters is produced the user inputs a pair of charaters(two letters) and my code should check if that pair is in the random array that was produced. it worked fine when it just checked for one letter but when i introduced the second one it does not work.I would appreciate any help.
#include <ctime>
#include <iostream>
#include <cstdlib>
int main() {
std::srand(std::time(NULL));
int i, num;
char letter1, letter2, ch, r;
const char chars[]="abcdefghijklmnopqrstuvwxyz";
std::cout << "How many letters do you want in your string? ";
std::cin >> num;
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
std::cout << "\nWhat letter pair would you like to find? ";
std::cin >> letter1 >> letter2;
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
}

First, you are not storing your randomly generated chars
for (i=0; i<num; i++)
{
ch = chars[rand()%26];
std::cout << ch;
}
This just writes a random char in ch and displays it on the console with each iteration. You don't store your data, ch just contains the last random char after your loop ends and everything else is lost.
The part where you want to search is double wrong.
if ((chars[i] == letter1) && (chars[i+1]==letter2))
std::cout << "It is in your string. ";
else
std::cout << "You do not have " << letter1 << letter2 << " in your string";
This isn't inside a loop, i is simply always going to be num-1.
The array you are checking is chars which is your const array containing "abcdefghijklmnopqrstuvwxyz". This doesn't contain your randomly generated chars.

Related

String array filled with random names

It's the first time I'm trying something with String Arrays in C++ and yep... I'm stuck.
I'm trying a small programm which will let the user enter max. 10 random Names. If the user enters '.' or has entered 10 nNames the input dialog will end. After he has done this all names will be printed out.
I tried it with a vector, but I guess I be doing something completely wrong...
#include <iostream>
#include <vector>
using namespace std;
int main()
{
char name;
int i, counter;
vector<string> namen_vec;
cout << endl << "Eingabedialog von maximal 10 Namen. " << endl;
cout << "Eingabe kann fruehzeitig mit '.' beendet werden. " << endl;
cout << "--------------------------------------------------" << endl << endl;
counter = 0;
do
{
cout << "Eingabe Name: ";
cin >> name;
namen_vec.push_back(name);
counter++;
} while (name != '.' && counter <= 9);
for (int i = 0; i < namen_vec.size(); i++)
{
cout << namen_vec[i] << endl;
}
return 0;
}
Maybe someone has one or two advices?
First of all, you have declared the variable name as char but your container vector namen_vec accepts a string. Still, the program won't be compiled successfully because the following line
while (name != '.' && counter <= 9);
as name would be a string then you have to change this as
while (name != "." && counter <= 9);

How to fix output from repeating cout from IF/ELSE statments

I have a completed code for my class; it creates a randomized string based on how many characters that the user asks for, and it then allows for the user to specify if they want to find a particular pair of characters in the string. That last part is based on a if/else statement that either gives the location, or is suppose to tell them there is no pair in the string.
My issue is that, when given a pair to find, if its in the string it gives the corrected statement, however, it also gives the else statement, repeated several times. if the pair is not in the string, it then gives the correct else statement, but repeats the cout several times. I don't know how to solve this issue.
Here is my code and screen shots of my outputs.
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
int i=0, n;
char alphabet[26];
char RandomStringArray [100];
char Ltr1, Ltr2;
srand(time(0));
cout <<"How many letters do you want in your random string (no less than 0, no more than 100): ";
cin >> n;
for (int i=0; i<=25; i++)
alphabet[i] = 'a' + i;
while(i<n) {
int temp = rand() % 26;
RandomStringArray[i] = alphabet[temp];
i++;
}
for(i=0; i<n; i++)
cout<<RandomStringArray[i];
cout<<"\n";
cout<<"What letter pair would you like to find? ";
cin>>Ltr1>>Ltr2;
for (i=0; i<n; i++)
if (Ltr1==RandomStringArray[i] && Ltr2== RandomStringArray[i+1]){
cout<<"The pair is in the string starting at character number "<<i+1<<" in the string. \n";
}
else if (Ltr1!=RandomStringArray[i] && Ltr2!= RandomStringArray[i+1])
cout<<"no";
return 0;
}
Your final for loop is looping through every character in the random string from begin to end, which is fine for searching, but it is outputting the result of comparing every character, which is not what you want. Don't display any output at all until the loop is finished, eg:
for (i = 0; i < (n-1); i++)
{
if (RandomStringArray[i] == Ltr1 && RandomStringArray[i+1] == Ltr2)
break;
}
if (i < (n-1))
cout << "The pair is in the string starting at character number " << i+1 << " in the string.\n";
else
cout << "The pair is not found in the string.\n";
I would suggest wrapping the search in a function, eg:
int findPair(const char *str, int len, char Letter1, char Letter2)
{
for (i = 0; i < (len-1); i++)
{
if (str[i] == Letter1 && str[i+1] == Letter2)
return i;
}
return -1;
}
...
i = findPair(RandomStringArray, n, Ltr1, Ltr2);
if (i != -1)
cout << "The pair is in the string starting at character number " << i+1 << " in the string.\n";
else
cout << "The pair is not found in the string.\n";
That being said, since you are using C++ anyway, you should go full C++, not a mix of C and C++, eg:
#include <iostream>
#include <string>
#include <random>
#include <algorithm>
int main() {
int n;
char alphabet[26];
std::string RandomString;
char LtrPair[2];
std::generate(std:begin(alphabet), std::end(alphabet), [ch = 'a'] () mutable { return ch++; } );
std::cout << "How many letters do you want in your random string: ";
std::cin >> n;
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 25);
RandomString.resize(n);
std::generate(RandomString.begin(), RandomString.end(), [&](){ return alphabet[dis(gen)]; };
std::cout << RandomString << "\n";
std::cout << "What letter pair would you like to find? ";
cin >> LtrPair[0] >> LtrPair[1];
auto pos = RandomString.find(LtrPair, 0, 2);
if (pos != std::string::npos)
std::cout << "The pair is in the string starting at character number " << pos+1 << " in the string.\n";
else
std::cout << "The pair is not found in the string.\n";
return 0;
}
Since you have placed your if...else construct inside of a for loop, it is evaluated every time. This means that for every instance where the first condition isn't true, the else clause is executed, causing your "no" message to repeat.

string and char variable was not declared in this scope C++

I want to create a program which is able to count the characters in a word.
This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask the user to input the word, at least contain 5 characters
do
{
string inputWord = "";
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
// ask the user to input a character
do
{
char searchCh = '0';
cout << "please enter a character from \n" << inputWord;
cin >> searchCh;
}while(searchCh.size()<1 && searchCH.size()>1);
// iterate over the word
for(int i=0;i < (int) inputWord.size(); i++)
{
// get the character
char ch = word.at(i);
// if the character matches the character we're looking for
if(searcCh==ch)
// increment counter
{
counter++; // counter = counter + 1
}
}
// output the number of times character appears
cout << "the word " << word << " contain character " << searchCh << "is" << counter;
return 0;
}
and I always get the error: inputWord was not declared.
What is the cause this error?
You should read about scopes. Variables in c++ have visibility and lifetime in scope, in which the were declared. For instance, inputWord is visible and exists only in the first do-while loop. Move its declaration above loop. Your code has many such errors. Moreover, I do not see, where is counter declared and it should be properly initialized.
You have mixed up a lot of variable names and used variables outside their scope.
Here is a working version of your code with a few debugs:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// ask the user to input the word, at least contain 5 characters
string inputWord = "";
char searchCh = '0';
char ch;
int counter=0;
do
{
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
// ask the user to input a character
cout << "please enter a character from \n" << inputWord;
cin >> searchCh;
// iterate over the word
for(int i=0;i < (int) inputWord.size(); i++)
{
// get the character
ch = inputWord[i];
// if the character matches the character we're looking for
if(searchCh==ch)
// increment counter
counter++; // counter = counter + 1
}
// output the number of times character appears
cout << "the word " << inputWord << " contain character " << searchCh << " is " << counter;
return 0;
}
You declared the inputWord as string, please check your compiler works for that or not because some compilers do not take the specifier "string". Also searchCh, counter and word is also missing from your program. First of all declare these variables properly.
you should define the "inputWord" before start the while loop , like this :
string inputWord = "";
do
{
cout << "please enter your word to be counted = \n";
cin >> inputWord;
}while(inputWord.size() < 5);
because "inputWord" is inside the loop ,

Check letters against the word of an arbitrary size in a Hangman game

Currently I am working on a hangman game, I had previously coded it to only work for a 5 letter word, but now would like to make it handle any length of word, how could I change this code to make it work how I want it to?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <cstdlib>
using namespace std;
int main()
{
string word;
int tries;
string guess;
string wordguess;
string output;
cout << "Enter a word for player two to guess: ";
cin >> word;
system("CLS");
cout.flush();
cout << "Guess the word!" << endl;
for (int i = 0; i < word.length(); i++)
{
cout << "_ ";
}
cout << "Enter a letter: ";
cin >> guess;
for (int tries = 5; tries > 0; tries--)
{
if (guess[0] == word[0]) {
output[0] = word[0];
cout << "You guessed the first letter! Good job!" << endl;
}
if (guess[0] == word[1]) {
output[2] = word[1];
cout << "You guessed the second letter! Good job!" << endl;
}
if (guess[0] == word[2]) {
output[4] = word[2];
cout << "You guessed the third letter! Good job!" << endl;
}
if (guess[0] == word[3]) {
output[6] = word[3];
cout << "You guessed the fourth letter! Good job!" << endl;
}
if (guess[0] == word[4]) {
output[8] = word[4];
cout << "You guessed the fifth letter! Good job!" << endl;
}
cout << output << endl;
cout << "You have " << tries << " tries left. Take a guess at the word: " << endl;
cin >> wordguess;
if (wordguess == word)
{
cout << "Congratulations, you guessed the word correctly!" << endl;
break;
}
}
system("pause");
return 0;
}
As you can tell I was checking each position from 0 to 4 (first through fifth letter). I know there are plenty of ways that I could have coded this better but as you can guess, I am new to coding and this is the way I thought of it. Please note this is still a work in progress so it is not fully complete. Any help would be great!
When designing an algorithm, think of how you would do this by hand, without a computer. Then let the code do the same.
If you were checking your friend's guess against a word written on sand, you would probably go about it like this:
go through the written pattern character by character, pronouncing your word in memory
for each letter, check if it is equal to the guess
if it is
replace the placeholder with it
memorize that your friend guessed right.
Also note if there are any placeholders left
if there aren't, your friend wins
finally, if your friend didn't guess right, score them a penalty point and check if they lose
Now, all that leaves is to put this down in C++. The language provides all sorts of entities - let's check which ones fit ours needs the best:
the word and the current pattern - strings of a fixed size
bits to memorize:
whether the current guess is right - bool
placeholders left - int
penalty points (or, equivalently, attempts left) - int
parts of the algorithm:
looping over a string - for loop of one of a few kinds
we need to replace the character in the pattern at the same index as the guessed letter in the word. So, we need to have the index when looping. Thus the flavor with the index variable, for(std::string::size_type i = 0; i < str.size(); ++i) probably fits the best.
// Example program
#include <iostream>
#include <string>
using namespace std;
class my_game
{
private:
string congrats_array[15] = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "nineth", "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth"};
string word_to_guess;
int tries_left;
int word_length;
int letters_guessed_count;
string guessed_letters;
void check_letter(char letter);
void print_current_word_state();
public:
my_game();
void begin_the_game();
void play_the_game();
};
my_game::my_game()
{
}
void my_game::begin_the_game()
{
cout << "Enter a word for player to guess: " << endl;
cin >> word_to_guess;
system("CLS");
cout.flush();
cout << "Enter the tries amount!\n" << endl;
cin >> tries_left;
word_length = word_to_guess.size();
guessed_letters = "_";
letters_guessed_count = 0;
for(int i = 0; i < word_length - 1; i++){
guessed_letters += "_";
}
}
void my_game::play_the_game()
{
cout << "Guess the word!" << endl;
char letter;
for(int i = 0; i < tries_left; i++)
{
cout << guessed_letters << endl;
cout << "Enter a letter: " << endl;
cin >> letter;
check_letter(letter);
if(letters_guessed_count == word_length){
cout << "Congrats! You won!" << endl;
return;
}
}
cout << "You lose" << endl;
}
void my_game::check_letter(char letter)
{
for(int i = 0; i < word_length; i++)
{
if(word_to_guess[i] == letter && guessed_letters[i] != letter)
{
guessed_letters[i] = letter;
letters_guessed_count++;
cout << "You guessed the" << congrats_array[i] <<"letter! Good job!" << endl;
}
}
}
int main()
{
my_game game;
game.begin_the_game();
game.play_the_game();
}
So, in short what you need to do this with words of any arbitrary length is to use string's .substr() function and the stringstream library's .str() and << and >> operators. This version of your code uses a function that inserts a correctly guessed character at the appropriate indexed location. This will gradually replace the "_________" with letters at the correct places. This is much easier to do in Java, but stringstream is a good library I would highly recommend getting familiar with it. I'll leave the problem of how to handle multiple instances of a guessed character up to you (ie 'i' in "bibliography")
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
string newString(string, int, string);
int main()
{
string word;
string guess;
int tries;
string output;
string input;
cout << "Enter word for player 2 to guess: ";
cin >> word;
stringstream ss;
//---------- fills the stream with "_"s matching the length of word
for(int i = 0; i < word.length(); i++)
ss << "_";
//----------- assigns the initial value of "___..." to output
ss >> output;
//----------- sets up the loop
tries = 5;
bool found = false;
for(int i = 0; i < 5; i++)
{
cout << "\nTry " << i << " of 5: Enter a letter or guess the word: ";
cin >> input;
if(input == word)
{
cout << "Congratulations, you guessed the word correctly!" << endl;
break;
}
//------------------ else, proceed with replacing letters
if(word.find(input) != std::string::npos)
{
size_t position = word.find(input); // finds index of first instance of the guessed letter
cout << "You guessed the " << position+1 << " letter! Good job!" << endl; // since strings start at index 0, position+1
//------- replaces appropriate "_" with the guessed letter
output = newString(input, position, output);
cout << "\n" << output;
// Around here you'll want to set up a way to deal with multiple instances
// of the same letter
}
else
cout << "Incorrect guess" << endl;
}
return 0;
}
//---------------------------------------------------
string newString(string guess, int index, string word)
{
string NewString;
stringstream temp;
//---------- hack up the string into sections before and after the index
string before = word.substr(0, index);
string after = word.substr(index+1, word.length() - index+1);
//---------------- populates the new stringstream and assigns it to the result
temp << before << guess << after;
NewString = temp.str();
return NewString;
}

Program that counts the number of types of letters in a paragraph, C++

What I want is to have a multiple-line text input, and to be able to count the number of lower-case letters, upper-case letters, periods, commas, spaces, line-breaks, and other characters in the input.
I am trying to use just one string with getline for inputs in a while loop with a running count for each punctuation category.
I just don't know how to actually figure out how many of each character type there are in each line. Given a string, how do I count the number of each type?
Here is my code so far (obviously incomplete):
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
#include <string>
using namespace std;
int main(){
cout << "This program takes any number of sentences as inputs. " << endl;
cout << "It will count the number of lower-case letters and upper-case letters. " << endl;
cout << "It will also count the number of periods, exclamation marks, spaces, end-lines, etc. " << endl;
cout << " " << endl;
cout << "Please type your text, pressing enter whenever you wish to end a line. " << endl;
cout << "Use the EOF key (CTRL + Z on Windows) when you are finished. " << endl;
string InputString; // This is the string that will be used iteratively, for each line.
int NumberOfLowerCase = 0;
int NumberOfUpperCase = 0;
int NumberOfSpaces = 0; // spaces
int NumberOfTabs = 0; // tabs
int NumberOfPeriods = 0; // periods
int NumberOfCommas = 0; // commas
int NumberOfOtherChars = 0; // other characters
int NumberOfEnters = 0; // end of line, will be incremented each loop
do {
getline(cin, InputString); // input
cout << InputString << endl; // filler just to test the input
NumberOfLowerCase = NumberOfLowerCase + 0 // I don't know what I should be adding
// (obviously not zero, that's just a filler)
} while (!cin.eof() && cin.good());
system("pause");
return 0;
}
If you simply want the number of unique characters, use a set! You can push all of your characters into the set and then just check how big the set is and you'll be good to go!
If you actually want to know how many of each character there are you can use a map (which in fact uses a set under the hood!). With the map, given some character c, you could do
std::map<char, int> counter;
//do stuff...
counter[c]++; //increment the number of character c we've found
//do more stuff...
std::cout << "Found " << counter['A'] << " A's!" << std::endl;
See these helpful functions. Here what you would do:
std::string s = /*...*/;
for(auto c : s) {
if(std::islower(c)) ++NumberOfLowerCase;
else if(std::isupper(c)) ++NumberOfUpperCase;
else if(c == ' ') ++NumberOfSpaces;
else if(c == '\t') ++NumberOfTabs;
else if(c == '.') ++NumberOfPeriods;
else if(c == ',') ++NumberOfCommas;
else ++NumberOfOtherChars;
}
Here's a very simple example I wrote very quickly. Of course there are better ways of doing it, but this should give you an idea of how you could do that. One question: Are you reading from a file or from an istream directly from the console?
int lowerCase = 0;
int upperCase = 0;
int spaces = 0; // spaces
int tabs = 0; // tabs
int newLines = 0; // end of line, will be incremented each loop
int periods = 0; // periods
int commas = 0; // commas
int otherChars = 0;
// read from istream, char by char
for (char ch; cin >> noskipws >> ch;) {
// test which classification or char ch is and increment its count
if (islower(ch))
++lowerCase;
else if (isupper(ch))
++upperCase;
else if (ch == ' ')
++spaces;
else if (ch == '\t')
++tabs;
else if (ch == '\n')
++newLines;
else if (ch == '.')
++periods;
else if (ch == ',')
++commas;
else
++otherChars;
}
cout << "Number of characters of each type:\n";
cout << "lowerCase:\t" << lowerCase << '\n'
<< "upperCase:\t" << upperCase << '\n'
<< "spaces:\t\t" << spaces << '\n'
<< "tabs:\t\t" << tabs << '\n'
<< "periods:\t" << periods << '\n'
<< "commas:\t\t" << commas << '\n'
<< "newLines:\t" << newLines << '\n'
<< "otherChars:\t" << otherChars << '\n';