So I have these two functions at the top of my program:
string deletespaces(string sentence){
sentence.erase(std::remove(sentence.begin(), sentence.end(), ' '), sentence.end());
return sentence;
}
and
string checkpalindrome(string sentence){
deletespaces(sentence);
if (sentence == string(sentence.rbegin(), sentence.rend())){
cout << sentence << " is a palindrome." << endl;
}
if(sentence != string(sentence.rbegin(), sentence.rend())){
cout << sentence << " isn't a palindrome." << endl;
}
}
This is my main body of code.
int main(){
int x = 1;
string originalsentence;
while (x == 1) {
int a = 1;
int input;
string sentence;
cout << "Press 1 to reverse a string, 2 to check a palindrome, and anything else to quit: ";
cin >> input;
if(input == 1) {
cout << "Enter a sentence to reverse: ";
cin.ignore();
getline(cin,originalsentence);
originalsentence = sentence;
cout << string(sentence.rbegin(), sentence.rend()) << endl;
}
if(input == 2) {
cout << "Enter a sentence to check: ";
cin.ignore();
getline(cin,originalsentence);
originalsentence = sentence;
checkpalindrome(sentence);
}
cout << "Hit 1 if you want to continue, anything else to quit: ";
cin >> x;
}
}
So here is my problem. I am able to put in my choice about whether to reverse a string or check whether the string is a palindrome. However, when I try to reverse the string, it simply gives a blank line, then asks whether I want to continue. When I ask to check a palindrome, it simply says "is a palindrome" regardless of what I input. Any ideas?
Related
#include <iostream>
#include <string>//needed to make string array
#include <fstream>//Needed for redaing in from external file
#include <cstdlib>//needed for rand() function (for random word)
#include <ctime>//needed for time() funtion to seed rand()
using namespace std;
/*
April 25,2020
This program will take read in a random word from an external file and use it for a game of hang man */
void greeting();
void wordPick();
int main()
{
char playAgain;
int tries;
char playerGuess;
string secretWord;
greeting();
ifstream inFile("randwords.txt");
if (inFile.is_open())
{
string wordlist[10];
for(int i = 0; i < 10; ++i)
{
inFile >> wordlist[i];
}
srand(time(0));
string secretword = wordlist[rand() % 10];
cout << secretword << endl;
inFile.close();
}
//wordPick();
//ask user to guess a letter
cout << "Please guess a letter: " << endl;
cin >> playerGuess;
if (playerGuess == secretWord[0])
{
cout << "Thats correct!" << secretWord [0];
}
else if (playerGuess == secretWord[1])
{
cout << "thats correct!" << secretWord[1];
}
else if (playerGuess == secretWord[2])
{
cout << "Thats correct!" << secretWord[2];
}
cout << "Do you want to play again? Y or N: ";
cin >> playAgain;
while (playAgain != 'Y' && playAgain != 'y' && playAgain != 'N' && playAgain != 'n')
{
cout << "Invalid, please enter Y or N: ";
cin >> playAgain;
}
return 0;
}
void wordPick()//reads in external file and puts it in an array for a library of words to randomly choose
{
ifstream inFile("randwords.txt");
if (inFile.is_open())
{
string wordlist[10];
for(int i = 0; i < 10; ++i)
{
inFile >> wordlist[i];
}
srand(time(0));
string secretword = wordlist[rand() % 10];
// cout << secretword << endl;
inFile.close();
}
}
void greeting()//welcomes the player to the game and starts the game
{
string name;
cout << "Hello, Player welcome to Hangman! " << endl;
cout << "What should I call you?" << endl;
cin >> name;
cout << "Hello " << name << ", in this game you will try to guess a random 3 letter word." << endl;
cout << "You will have at least 6 ties to guess the word or else the drawing will complete. Good luck!" << endl;
What I am attempting to do is to check if the char playerGuess is one of the characters in string secretWord, but it isn't outputting the letter even if it is correct. Maybe there is an easier way to compare that I'm just missing?
I thought since this still compares that it should work, but it's just ending the program after guessing the letter.
You assigned the randomly chosen word to secretword (with small w), but the judge is based on secretWord (with large W), to which no word is assigned.
The part
string secretword = wordlist[rand() % 10];
cout << secretword << endl;
should be
secretWord = wordlist[rand() % 10];
cout << secretWord << endl;
Also note that you mustn't declare secretWord in the if block, or the assignment won't be visible to the judge part.
I'm having trouble with understanding how to output the inverse of the string then store the inverse value and apply it to a string variable to print the string later on. Some errors I receive depending on the structure of the program include : random characters being printed, just the string input being printed, the programming crashing... The program must be able to process this menu:
At one point I had the inverse working, but when I would add for example if(choice == '2') and create the reverse function it would start acting up again.
This is what I have for now :
int main()
{
string userString = "";
int i = 0;
char choice;
char invChar = char(userString[i]);
userString = invChar;
cout << "Please enter a word, a sentence, or a string of numbers." << endl;
getline(cin, userString);
do
{
cout << "\nUSE THIS MENU TO MAINPULATE YOUR STRING\n"
<< "----------------------------------------" << endl;
cout << "1) Inverse String\n"
<< "2) Reverse String\n"
<< "3) To Uppercase\n"
<< "4) Count Number Words\n"
<< "5) Count Consonants\n"
<< "6) Enter a Different String\n"
<< "7) Print the String\n"
<< "Q) Quit" << endl;
cin >> choice;
cin.ignore();
if (choice == '1')
{
for (int i = 0; i <= userString.length(); ++i)
{
if (isupper(userString[i]))
{
char(tolower(userString[i])); // if uppercase - converts to lower - if upper keeps value
invChar += userString[i];
}
userString = invChar;
}
cout << userString;
}
} while (choice != 'q' || choice != 'Q');
Thanks in advance for any tips and tricks!
Did you maybe mean to do this:
for (int i = 0; i < userString.length(); ++i)
{
if (isupper(userString[i]))
{
userString[i] = (tolower(userString[i]));
}
else if(islower(userString[i]))
{
userString[i] = (toupper(userString[i]));
}
}
This will actually inverse. What you were doing before doesn't work, and also only converts to uppercase
The explanation:
Working with two input streams streams, both use getline() to capture the user input. The first getline() is called in the userStringPrompt() function:
string userStringPrompt()
{
string userString;
cout << "Enter a string: ";
getline(cin, userString);
return userString;
}
That sets a string that the program will use later to perform functions, like count its consonants, its vowels, etc.
The second input is used in the menu selection (choose what function/method to perform on the above string):
string userMenuPrompt()
{
string userString;
getline(cin, userString);
return userString;
}
This takes in a user input: A, B, C, D, E and performs an action. For example, if a user inputs into the first input stream:
Hello
and then enter "A" in the second input stream, it should count the vowels in hello, then return the number from the calculation, e.g. 2
The issue:
The program functions correctly when the input in userStringPrompt is without spaces. For example, Hello works, but Hello World would break the application and cause a force close. I'm not sure why, since I am capturing the stream with getline(cin, string).
The entire code:
#include <string>
#include <iostream>
using namespace std;
string userStringPrompt();
string userMenuPrompt();
void showMenu();
int countConsonants(string *ptr);
int countVowels(string *ptr);
int countConsonantsVowels(string *ptr);
int main()
{
string userInput = "";
string userString;
bool userStringSet = false;
while (userInput != "e") {
if (!userStringSet) {
userString = userStringPrompt();
userStringSet = true;
}
showMenu();
userInput = userMenuPrompt();
string *pointerVariable = &userString;
if (userInput == "a") {
cout << endl;
cout << "Vowel count in \"" << userString << "\": " << countVowels(pointerVariable) << endl;
cout << endl;
break;
}
if (userInput == "b") {
cout << endl;
cout << "Consonants count in \"" << userString << "\": " << countConsonants(pointerVariable) << endl;
cout << endl;
break;
}
if (userInput == "c") {
cout << endl;
cout << "Vowel count in \"" << userString << "\": " << countVowels(pointerVariable) << endl;
cout << "Consonants count in \"" << userString << "\": " << countConsonants(pointerVariable) << endl;
cout << endl;
break;
}
if (userInput == "d") {
userStringSet = false;
break;
}
}
return 0;
}
int countConsonants(string *ptr) {
string getVar = *ptr;
int stringSize = getVar.length();
int vowelCount = countVowels(ptr);
int totalConsonants = stringSize - vowelCount;
return totalConsonants;
}
int countVowels(string *ptr) {
int vowelsToCount = 0;
string stringVar = *ptr;
for (int i = 0; i < stringVar.length(); i++){
if (tolower(stringVar[i]) == 'a' || tolower(stringVar[i]) == 'e' || tolower(stringVar[i]) == 'i' || tolower(stringVar[i]) == 'o' || tolower(stringVar[i]) == 'u') {
vowelsToCount++;
}
}
return vowelsToCount;
}
int countConsonantsVowels(string *ptr) {
int count = countConsonants(ptr);
count += countVowels(ptr);
return count;
}
string userStringPrompt()
{
string userString;
cout << "Enter a string: ";
getline(cin, userString);
return userString;
}
string userMenuPrompt()
{
string userString;
getline(cin, userString);
return userString;
}
void showMenu() {
cout << "A) Count the number of vowels in the stream" << endl;
cout << "B) Count the number of consonants in the stream" << endl;
cout << "C) Count both the vowels and consonants in the stream" << endl;
cout << "D) Enter another string" << endl;
cout << "E) Exit the program" << endl;
}
Any guidance/hints would be greatly appreciated. I'm absolutely confused.
I guess your program is not crushing, it's just normally exits.
The program '[8776] Chapter10.exe' has exited with code 0 (0x0).
which is ok, no error code returned.
When you run your program it asks for input, do its work and because there is no more work for it - exits. To see the output you can do one of the following:
Try to run it with Ctrl + F5 in VS, it will add pause command to the end.
Another way to run it is to open command line and run it from there.
Also in your case I guess the problem is in break statements. When you choose what to do with the string you break your loop (which should run while user enters e). Remove all breaks and it will be fine.
So i have a palindrome program and here are the codes:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
void palindrome();
void compareTwoInt();
bool validation(const string&);
int main()
{
int selection;
cout << "\t\t\t MENU\n";
cout << "\t\t\t ----\n";
cout << "\t\t\t1. Palindrome";
cout << "\n\t\t\t2. Compare Two Integers";
cout << "\n\t\t\t3. End program\n";
cout << "\n\t\t\tEnter your choice : ";
cin >> selection;
while (selection < 0 || selection > 4)
{
cout << "\t\t\nInvalid entry. Please enter an appropriate entry.";
cout << "\n\n \t\t\tEnter your choice: ";
cin >> selection;
}
if (selection == 1)
{
cout << "Enter a word, phrase, sentence: \n";
string input;
getline(cin, input);
string input2;
for (unsigned int i = 0; i < input.length(); i++)
{
if (isalnum(input[i]))
{
input2 += toupper(input[i]);
}
}
cout << input2 << endl;
if (validation(input2))
{
cout << "The phrase is a palindrome!" << endl;
cout << "Press <Enter> key back to menu" << endl;
}
else
{
cout << "The phrase is not a palindrome!" << endl;
cout << "Press <Enter> key back to menu" << endl;
}
fflush(stdin);
cin.get();
system("cls");
return main();
}
else if (selection == 2)
{
compareTwoInt();
fflush(stdin);
system("cls");
return main();
}
else if (selection == 3)
{
cout << "\t\t Good Bye. Press <Enter> key to End the program.\n";
}
fflush(stdin);
cin.get();
return 0;
}
void compareTwoInt()
{
int first, second;
cout << "\n\nEnter your positive integer : ";
cin >> first;
cout << "\nEnter your positive integer : ";
cin >> second;
fflush(stdin);
cin.get();
}
bool validation(const string& input)
{
return input == string(input.rbegin(), input.rend());
}
for some reason when i choose 1 for the palindrome, it doesn't let me write the words, (in another words, it doesn't let me input)
the console just says:
Enter a word, phrase, sentence:
The phrase is palindrome!
Press key back to menu
Anybody have an idea how to fix this?
Thanks in advance!
When you choose 1 for the palindrome, you hit enter. Thus your input consists of the number 1 followed by a newline. Your cin >> selection; reads the number 1 and then your getline(cin, input); reads the newline, which it interprets as an empty line. You have written no code to do anything sensible with the newline character input after the number, so nothing sensible happens.
Try typing 1foof<enter> instead. Your code will read that as a 1 followed by a line containing foof.
When a user enters spaces in between digits to create a reference string it throws everything off and will even carry numbers over to the next cin. If however they have letters in between and no spaces it works fine. The assignment was for a page replacement sim.
Code (this is only the part of the code that should effect my problem):
void main()
{
bool again = false;
bool reuse = false;
bool valid;
int use;
int refLength;
vector<int> ref(0);
vector<frame> frames(0);
string refString;
string user;
//ask how long the user wants the ref string to be
do{
valid = false;
while (!valid&&!reuse)//take choice of ref string
{
cout << "How long do you wish the reference string to be? ";
if (!(cin >> refLength))
{
cin.clear();//.clear and .ignore keep cin from errors and forced infinite loop repeating following cout
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "The length must be enter as an integer value between ";
valid = false;
}
else
{
cout << "You have chosen to have a Ref string of " << refLength << " length " << endl;
valid = true;
}
}
valid = false;
while (!valid&&!reuse)
{
cout << "Do you want to enter a ref string or randomly generate one" << endl;
cout << "of your chosen length? Enter 1 to generate and 2 to input the string ";
if (!(cin >> use) | (use<0 || use>2))
{
cin.clear();//.clear and .ignore keep cin from errors and forced infinite loop repeating following cout
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You must enter an integer between 1 and 2";
}
else
{
valid = true;
if (use == 1)
{
make(ref, refLength);
}
else
{
cout << "please enter a ref string of chosen length entering" << endl;
cout << "fewer digits will cause 0's to be added. Entering more" << endl;
cout << "will cause those past the chosen length to be dropped " << endl;
cout << "any letters will be ignored but spaces throw things off" << endl;
cout << "Also all entries must be single digit integers (0-9) " << endl;
cin >> refString;
make(ref, refLength, refString);
}
use = 0;
}
}
cout << endl;
/*for(int i=0;i<ref.size();i++)
{
cout<<ref[i]<<" ";
}*/
valid = false;
while (!valid)
{
cin.clear();
//errors ********************************************88
cout << "How many frames do you want (1-7) ";
if (!(cin >> use) | (use<0 || use>7))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "You must enter an integer between 1 and 7 ";
valid = false;
}
else
{
valid = true;
setUpFrames(use, frames);
use = 0;
}
}
valid = false;
while (!valid)
{
cout << "Enter 1 for FIFO or 2 for LRU pageRep algo or 3 for Optimal";
if (!(cin >> use) | (use<0 || use>3))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Must be int between 1 and 3";
}
else if (use == 1)
{
cout << endl << "# of Page Faults ";
cout << FIFO(ref, frames);
valid = true;
}
else if (use == 2)
{
cout << endl << "# of Page Faults ";
cout << LRU(ref, frames);
valid = true;
}
else
{
cout << endl << "# of Page Faults ";
cout << Optimal(ref, frames);
valid = true;
}
}
cout << endl;
cout << "do you want to try again ? Enter y for yes anything else for no" << endl;
cin >> user;
if (user == "y")
{
again = true;
cout << "do you want to use the same reference string? y for yes anything else for no" << endl;
cin >> user;
if (user == "y")
{
reuse = true;
}
else
{
reuse = false;
}
}
else
{
again = false;
}
} while (again);
}
If you want cin/cout interaction word/line by word/line use getline, otherwise confusion will arise.