English to Morse code program - c++

#include <iostream>
#include <iomanip>
#include <conio.h>
#include <stdlib.h>
#include <string>
using namespace std;
int main()
{
string text[39] = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9","0","Stop",",","?"};
string code[39] = {".-","-...","-.-.","-..",".","..-","--.","....","..",".---","-.-",".-..","--",
"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..",
".----","..---","...--","....-",".....","-....","--....","---..","----.","-----",".-.-.-","--..--","..--.."};
string English, Morse, output_string;
int option, string_size = 0, location;
char again = 'y', letter;
while(again == 'y')
{
system("cls");
cout << "1 - Encode(Text to Morse)\n";
cout << "2 - Decode(Morse Code to Text)\n";
cout << "3 - Display the Morse Code\n";
cout << "4 - Quit\n";
cout << "Enter 1,2,3 or 4:";
cin >> option;
cin.ignore(256,'\n');
system("cls");
switch(option)
{
case 1:
cout << "\nEnter a string with multiple words to encode:";
getline(cin, English);
system("cls");
cout << "\nThe target string to be translated is:" << "\n";
cout << English << "\n";
string_size = English.length();
for(int n = 0; n <= string_size-1; n++)
{
letter = (char)English.at(n);
if(letter != ' ')
{
for(int t = 0; t <=39; t++)
{
if(letter == text[t])
{
cout << code[t] << " ";
break;
}
}
}
else if(letter == ' ')
{
cout << "\n";
}
}
getch();
break;
}
}
}
I didn't finish it yet, but I don't know why I can't run if(letter == text[t]), it says it's an error. how can I fix it? And I have no idea to write the code that Morse to English. how can I know the position of the array that the user entered?
Error message:
error: no match for 'operator==' (operand types are 'char' and 'std::string {aka std::basic_string}')|

You are trying to compare between strings and char.
You need to write the array like that (if you want to use just characters):
char text[39] = {'A','B','C','D','E','F','G','H','I','J','K','L','M'};
and not:
string text[39] = {"A","B","C","D","E","F","G","H","I","J","K","L","M"};

for (int t = 0; t <= 39; t++)
You have 39 items starting at zero index, therefore your loop should go up to (but not including) 39
for (int t = 0; t < 39; t++)
{
...
}
You can declare a temporary string to copy each letter to string. You would also need to make sure text is upper case:
letter = (char)English.at(n);
if (letter != ' ')
{
for (int t = 0; t < 39; t++)
{
std::string temp;
temp = toupper(letter);
if (temp == text[t])
{
cout << code[t] << " ";
break;
}
}
}

If you want the array to be string - then use strcmp() function.
if(strcmp(text[t],letter)==0)
{
cout << code[t] << " ";
break;
}
Have a good luck!

Related

Pig latin conversion using Cstrings

The program takes in a word given by the user and translates that to pig latin. I've gotten everything to work almost perfectly, but have run into two bugs. The first of which is when translating words that begin with consonants say "count", the output is "ounttcay" instead of "ountcay". The second bug is that when for three letter words like "egg" or "not" the output is "egg_\377ay" or "ottn\377ay". Is there a simple way to remove that duplicate character and get rid of those numbers?
Note - Unfortunately it has to be done using a Cstring
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
int convertToPigLatin(char arr[50]);
bool isVowel(char ch);
int main() {
char userInput[50];
char answer = ' ';
do {
cout << "Enter a word to convert it to pig latin" << endl;
cin.getline(userInput, 50); //get user input
cout << "Your entered word is " << userInput << endl;
convertToPigLatin(userInput); //translate user's input into piglatin
cout << "Would you like to convert another word?" << endl;
cin >> answer;
cin.ignore(); //clear past user input
cin.clear();
} while (answer == 'Y' || answer == 'y');
return 0;
}
bool isVowel (char ch) {
switch (tolower(ch)) { //if the first character of the given input is a vowel
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
return true;
default:
return false;
}
}
int convertToPigLatin(char arr[50]) {
char newArr[50];
// string conjunctions[6] = {"and","but","for","nor","yet","the"}; //list of conjunctions not to be converted
size_t arrLength = strlen(arr); //holds length of input
for (int i = 0; i < arrLength; i++) { //make sure all characters in input are lower case for easier processing
newArr[i] = tolower(arr[i]);
}
char lastChar = newArr[0]; //save the first character in case it needs to be appended
if (atoi(arr) || arr[0] == '\0') { //if the input contains a number or begins with a null character print an error
cout << "Cannot translate inputs that contain numbers" << endl;
return -1;
} else if (arrLength <= 2) { // if the input is 2 or less characters
cout << newArr << endl; //print the input as is
cout << "Boring! Try somthing more than 2 characters long" << endl;
return 0;
} else if ((strstr(newArr, "and") && arrLength == 3) || (arrLength == 3 && strstr(newArr, "but")) || (arrLength == 3 && strstr(newArr, "for")) || (arrLength == 3 && strstr(newArr, "nor")) || (arrLength == 3 && strstr(newArr, "yet")) || (arrLength == 3 && strstr(newArr, "the"))) { //if the input is more than 2 characters long
cout << newArr << endl; //print the input as is
cout << "No conjucntions try again!" << endl;
return 0;
} else { //if the given input is three characters and is not a conjunction, being translation
if (isVowel(arr[0])) { //check if input's first character is a vowel
cout << "Your word in piglatin is "<< strcat(newArr, "ay") << endl; //print that string with 'ay' at the end (i.e. egg'ay')
return 0;
} else { //else if the given input starts with a consonant
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
newArr[arrLength] = lastChar;
}
cout << "Your word in piglatin is " << strcat(newArr, "ay") << endl;
return 0;
}
}
return 0;
}
You're not terminating newArr, and the last index of the input string is arrLength - 1.
int convertToPigLatin(char arr[50]) {
// Make sure newArr is properly terminated.
char newArr[50] = {0};
// [...]
} else { //else if the given input starts with a consonant
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
}
// Do this outside the loop.
newArr[arrLength-1] = lastChar;
// No need for strcat here.
cout << "Your word in piglatin is " << newArr << "ay" << endl;
}
}
return 0;
}
You need to add the '\0' at the end of newArr because strlen does not count it so you are not copying it. strcat replaces '\0' witn 'ay\0' but you have no '\0'.
for (int r = 1; r < arrLength; r++) {
newArr[r-1] = newArr[r];
newArr[arrLength] = lastChar;
}
newArr[arrLength+1] = '\0';
cout << "Your word in piglatin is " << strcat(newArr, "ay") << endl;

I want to remove occurrences of a given letter

I have attempted to remove the occurrences of a user inputted letter after they've chosen a word however, the final output prints out a random string of letters and numbers instead of what I expected. For example, if the user enters the text "Coffee" then proceeds to enter the letter "f", the program should return "Coee" as the final print. However, this is not the case. Could anyone check to see where I've gone wrong? Much obliged.
#include <iostream>
#include <string>
using namespace std;
void removeAllOccurrence(char text[], char letter)
{
int off;
int i;
i = off = 0;
if (text[i] == letter)
{
off++;
}
text[i] = text[i + off];
}
int main() {
string text;
char letter;
string newText;
cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;
cout << "your new text is: " << removeAllOccurrence << endl;
system("pause");
return 0;
}
This should do the job
#include <algorithm>
#include <string>
#include <iostream>
void remove_char(std::string s, char r) {
s.erase( std::remove( s.begin(), s.end(), r), s.end()) ;
std::cout << s << std::endl;
}
int main()
{
std::string test = "coffee";
char r = 'f';
remove_char(test, r);
return 0;
}
If u want to do this by hand try this:
std::string removeAllOccurrence(string text, char letter)
{
int off;
int i;
i = off = 0;
string out = "";
for (i = 0; i < text.size(); i++)
{
if (text[i] != letter)
{
out += text[i];
}
}
return out;
}
int main(void)
{
string text;
char letter;
string newText;
cout << "Type your text: " << endl;
cin >> text;
cout << "Choose the letters to remove: " << endl;
cin >> letter;
cout << "your new text is: " + removeAllOccurrence(text, letter) << endl;
system("pause");
return 0;
}
As you can see your main function was kinda right. You just need to pass some arguments into the function. Additonally you missed a loop in your remove function. If you use string in your main, why don't use string in yur function? You can just use string there, too
Kind Regards

How can I clean this code up by using a loop?

Basically, this program allows a user to enter a sentence and depending on the users selection, it will show the middle character of the sentence, display it uppercase or lowercase, or backwards. Simple program, but I am new to programming so that may be the problem. I would like to figure out how to use loops instead of a ton of if statements. When I try to make some loops it breaks certain parts of the code but I am sure that is because I don't properly understand them. If you have any criticism or any advice on the code, I'd be happy to hear it. Thanks in advance!
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
int sel;
string sent;
bool validinput;
int i;
int x;
int j;
int a;
cout << "Welcome to my program. Enter a sentence and select one of the options below.\n";
cout << "Enter -999 to exit the program." << endl;
cout << "============================================================================" << endl;
cout << endl;
cout << "1. Display the middle character if there is one." << endl;
cout << "2. Convert to uppercase." << endl;
cout << "3. Convert to lowercase." << endl;
cout << "4. Display backwards." << endl;
cout << "Enter a sentence: ";
getline (cin, sent);
cout << "Selection: ";
cin >> sel;
if (sel < 1 && sel > 4)
{
cout << "Invalid input. Try again. Selection: ";
cin >> sel;
validinput = false;
}
else (sel >= 1 && sel <= 4);
{
validinput = true;
}
if (validinput == true)
{
if (sel == 1)
{
j = sent.length() / 2;
cout << "The middle character is: " << sent.at(j) << endl;
}
if (sel == 2)
{
for (int i = 0; i < sent.length(); i++)
{
if (sent.at(i) >= 'a' && sent.at(i) <= 'z')
{
sent.at(i) = sent.at(i) - 'a' + 'A';
}
}
cout << "Uppercase: " << sent << endl;
}
if (sel == 3)
{
for (int x = 0; x < sent.length(); x++)
{
if (sent.at(x) >= 'A' && sent.at(x) <= 'Z')
{
sent.at(x) = sent.at(x) - 'A' + 'a';
}
}
cout << "Lowercase: " << sent << endl;
}
if (sel == 4)
{
for (a = sent.length() - 1; a >= 0; a--)
{
cout << sent.at(a);
}
}
}
system("pause");
return 0;
}
Personally I would use the switch selection statement. I roughly did this just to explain a bit on how it can make your code more friendly and understandable.
int sel;
bool validInput = false;
switch(sel)
{
case 1:
//display middle char if there's one
case 2:
//convert to uppercase
case 3:
//convert to lowercase
case 4:
//display backwards
validInput = true;
break;
default: //if number does not meat 1, 2, 3 or 4
validInput = false;
break;
}
As you may notice, for case 1, case 2, case 3 and case 4, there's a break just to say that if the number is between 1 to 4; validInput is true.
Reference: Switch Selection Statement
i suggest using a switch. It will organize your code better. From looking at your code you seem to have used for and if wisely. But I suggest the if statements checking for the input be replaced with switch.

C++ Hangman Swapping Underscores For Actual Chars

I am developing a Hangman game for an Uni assessment in C++ and I am having trouble displaying my hidden words after the user types a letter. So I have got the word being displayed as '_ _ _ _ _ _ _' but when I type a letter it doesn't swap the underscore for the actual letter.
game::game() {
words[0] = "strongly";
words[1] = "cheese";
words[2] = "computer";
words[3] = "coffee";
words[4] = "potatoes"; //words that can be in the game
words[5] = "zebra";
words[6] = "extinguisher";
words[7] = "solution";
words[8] = "diligent";
words[9] = "flabbergasted";
numGuesses = 0;
hiddenWord = words[rand() % 10]; //pick a random word from array words
completedWord = hiddenWord;
//for loop for changing the word to underscores
for (int i = 0; i < completedWord.length(); i++) {
completedWord[i] = '_';
}
//for loop adding a space after underscore
for (int i = 0; i < completedWord.length(); i++) {
cout << completedWord[i] << " ";
}
cout << endl;
cout << "Please enter a letter: ";
char guessedLetter;
cin >> guessedLetter;
if (guessedLetter = completedWord[0]) {
completedWord = guessedLetter;
//cout << guessedLetter << endl;
cout << completedWord << endl;
}
}
My whole program is separated into different header files and cpp files. So the code above is from my gameguesses.cpp and the header for that is below:
class game {
public:
string words[10];
game();
string hiddenWord;
int numGuesses;
string completedWord;
};
And this is what I actually get:
A help would be appreciated. Thank you!
I see 2 issues:
if (guessedLetter = completedWord[0])
That line needs == not =.
Secondly, you are comparing the guess only to the first letter of the hidden word. You need to write a loop to check each letter and substitute where it matches the guess, not just in element [0].
See if this helps.
#include <iostream>
#include <vector>
#include <string>
#include <stdlib.h>
#include <locale>
using namespace std;
class Game
{
public:
Game()
{
gameDictionary.push_back("strongly");
gameDictionary.push_back("cheese");
gameDictionary.push_back("computer");
gameDictionary.push_back("coffee");
gameDictionary.push_back("potatoes");
gameDictionary.push_back("zebra");
gameDictionary.push_back("extinguisher");
gameDictionary.push_back("solution");
gameDictionary.push_back("diligent");
gameDictionary.push_back("flabbergasted");
}
// Play until winning or losing. Returns true on win, false on loss.
bool playGame()
{
numGoodGuesses = 0;
numBadGuesses = 0;
numWordLettersFound = 0;
hiddenWord = gameDictionary[rand() % gameDictionary.size()]; //pick a random word from array words
guessedWordTracker = hiddenWord;
for (string::size_type i = 0; i < hiddenWord.size(); i++)
{
completedWord += "_ ";
}
for (;;)
{
cout << completedWord << endl;
cout << "Please enter a letter: ";
char guessedLetter;
do
{
cin >> guessedLetter;
guessedLetter = tolower(guessedLetter);
if (!isalpha(guessedLetter))
{
cout << "Invalid letter, try again." << endl;
}
} while (!isalpha(guessedLetter));
string::size_type pos;
int numMatchesFoundThisTime = 0;
while ((pos = guessedWordTracker.find_first_of(guessedLetter)) != string::npos)
{
completedWord[pos * 2] = guessedWordTracker[pos];
guessedWordTracker[pos] = '\x01';
numMatchesFoundThisTime++;
}
numWordLettersFound += numMatchesFoundThisTime;
if (numMatchesFoundThisTime > 0)
{
numGoodGuesses++;
cout << "Wow, you found " << numMatchesFoundThisTime
<< (numMatchesFoundThisTime > 1 ? " letters!" : " letter!")
<< endl;
if (numWordLettersFound == hiddenWord.size())
{
cout << "Congrats... the word is '" << hiddenWord << "' ... great job!" << endl;
return true;
}
}
else
{
numBadGuesses++;
cout << "Sorry, the letter '" << guessedLetter << "' is not in the word." << endl;
}
int totalGuesses = numGoodGuesses + numBadGuesses;
cout << "You've made " << numGoodGuesses << " good guesses, "
<< numBadGuesses << " bad guesses, "
<< totalGuesses << " total guesses." << endl;
// Example failure:
const int BAD_GUESSES_ALLOWED = 30;
if (numBadGuesses > BAD_GUESSES_ALLOWED)
{
cout << "Sorry, you have no more guesses left. You lose." << endl;
return false;
}
}
}
private:
vector<string> gameDictionary;
string hiddenWord;
string guessedWordTracker;
string completedWord;
int numGoodGuesses;
int numBadGuesses;
int numWordLettersFound;
};
int _tmain(int argc, _TCHAR* argv[])
{
Game g;
g.playGame();
return 0;
}

C++ - Replacing "_" with a character

Using C++, I'm trying to make a hangman game to become better at using C++ and programming in general. Anyways, the issue I'm facing is that I'm not sure how to replace the dashes within a string with the letter the user has guessed.
I think my problem is with the fact the word chosen is randomly chosen from an array and I'm not sure how to go about finding the positions within the randomly chosen string which consists of the guessed character.
I have commented out the area that's causing the issue.
#include <iostream>
#include <array>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <cstddef>
#include <algorithm>
using namespace std;
int main()
{
string words[3] = {"stack", "visual", "windows"};
string guess;
cout << "Welcome to hangman.\n";
cout << "\n";
srand(time(NULL));
int RandIndex = rand() % 3;
string selected = words[RandIndex];
for (int i = 1; i <= selected.size(); i++) {
cout << "_ ";
}
cout << "\n";
cout << "\nType in a letter: ";
cin >> guess;
cout << "\n";
if (selected.find(guess) != string::npos) {
/*for (int i = 1; i <= selected.size(); i++) {
if (selected.find(guess) != string::npos) {
cout << "_ ";
} else {
cout << guess << " ";
}
}*/
} else {
cout << "\nNay!\n";
cout << "\n";
}
cout << "\n";
cout << "\n";
system("PAUSE");
return 0;
}
I was thinking about using the replace() function but the problem I face here is that I'm not replacing the string within selected variable but sort of iterating through the word itself, if that made any sense whatsoever?
Use a second string, that is initialized with the underscores. If the find function doesn't return string::npos it returns the position in the string, and this is the same position you should change in the string with the underscores as well.
You actually need to use a second string to store the "guessed" string; this is because you need to keep track of all the guessed letters and display them.
something like :
string s ="test";
string t=""; //empty string
for(int i=0;i<s.size();i++)
t.append("_"); //initialize the guess string
cout<<t<<'\n';
char c;
cin >> c;
int pos = s.find(c); //get the first occurrence of the entered char
while(pos!=-1) //look for all occurrences and replaced them in the guess string
{
t.replace(pos,1,1,c);
pos = s.find(c, pos+1);
}
I think you need to maintain some extra state while looping - to keep track of which letters have / haven't been guessed.
You could add a new string current_state which is initially set to the same length as the word but all underscores. Then, when the player guesses a letter, you find all instances of that letter in the original word, and replace the underscore with the letter guessed, at all the positions found but in current_state.
First i would initialize a new string to show the hidden word:
string stringToDisplay = string( selected.length(), '_');
Then For each letter given by the user i would loop like this:
(assuming guess is letter)
size_t searchInitPos = 0;
size_t found = selected.find(guess, searchInitPos));
if (found == string::npos)
{
cout << "\nNay!\n";
cout << "\n";
}
while( found != string::npos)
{
stringToDisplay[found] = guess;
searchInitPos = found+1;
found = selected.find(guess, searchInitPos));
}
cout << stringToDisplay;
Hope this will help
I think it should be that:
string words[3] = {"stack", "visual", "windows"};
char guess;
string display;
cout << "Welcome to hangman.\n";
cout << "\n";
srand(time(NULL));
int RandIndex = rand() % 3;
string selected = words[RandIndex];
for (int i = 0; i < selected.size(); i++) {
display.insert(0, "_ ");
}
cout << display;
while(display.find("_ ") != string::npos) {
cout << "\n";
cout << "\nType in a letter: ";
cin >> guess;
cout << "\n";
bool flag = false;
for (int i = 0; i < selected.size(); i++) {
if (selected[i] == guess) {
display.replace(i*2, 1, 1, guess);
flag = true;
}
}
if (!flag) {
cout << "\nNay!\n";
cout << "\n";
} else {
cout << display;
}
}