Taking "exit" as user input in C++ - c++

I'm currently trying to write code that takes user input as strings, and then convert them to integers if I need to. If the user decides to enter exit then the program should move on to calling a function. Here is what I have so far:
void printArray(string string_array[], int size){
for (int i = 0; i < size; i++){
cout << string_array[i];
}
}
void a_func(){
string string_array[10];
string user_input;
while (user_input != "exit"){
cout << "Please enter a number between 0 - 100: ";
cin >> user_input;
if (stoi(user_input) < 0 || stoi(user_input) > 100){
cout << "Error, please re-enter the number between 0 - 100: ";
cin >> user_input;
}
else if (user_input == "exit"){
printArray(string_array, 10);
}
int array_index = stoi(user_input) / 10;
string_array[array_index] = "*";
}
However, as I'm testing the program, the console is aborting the program if I enter exit. Is there a way for me to enter exit and then the program calls printArray?

I think this changes in your code will solve the problem. Please, try with this code:
void printArray(string string_array[], int size){
for (int i = 0; i < size; i++){
cout << string_array[i];
}
}
void a_func(){
string string_array[10];
string user_input;
while (user_input != "exit"){
cout << "Please enter a number between 0 - 100: ";
cin >> user_input;
if (user_input == "exit"){
printArray(string_array, 10);
}
else if (stoi(user_input) < 0 || stoi(user_input) > 100){
cout << "Error, please re-enter the number between 0 - 100: ";
cin >> user_input;
int array_index = stoi(user_input) / 10;
string_array[array_index] = "*";
}
}
}
Hope this helps

stoi doesn't accept non-numbers. Try this:
#include <iostream>
using namespace std;
void printArray(string string_array[], int size){
for (int i = 0; i < size; i++){
cout << string_array[i];
}
}
void a_func(){
string string_array[10];
string user_input;
while (user_input != "exit"){
cout << "Please enter a number between 0 - 100: ";
cin >> user_input;
//cout << "You have printed " << user_input << endl;
bool isNumber = true;
for(string::const_iterator k = user_input.begin(); k != user_input.end(); ++k) {
if (isdigit(*k) == false) {
isNumber = false;
break;
}
}
if (isNumber) {
int number = stoi(user_input);
if (number < 0 || number > 100){
cout << "Error, please re-enter the number between 0 - 100: ";
continue;
} else {
int array_index = stoi(user_input) / 10;
string_array[array_index] = "*";
}
} else if (user_input == "exit"){
printArray(string_array, 10);
break;
} else {
// Not a number and not "exit"; do nothing?
}
}
}
int main() {
a_func();
return 0;
}

Related

Program Fails to output greatest integer

I am writing a program that takes multiple user inputs, and counts how many prime numbers there are, and which number is the greatest and smallest of the inputs. However, I am stuck. when I run the code, it thinks every new input is the greatest number. for example, if I enter 1, 2, 3, 2... It says the greatest number is 2. It takes the last integer inputted and thinks that is the greatest number. I have no started on the lease common number yet, but if I am able to understand how to get the greatest number, I bet I can get the least. Thanks guys!
#include <iostream>
using namespace std;
int main() {
int startstop = 1;
cout << "start program?" << endl;
int begin = 0;
int primecounter = 0;
cin >> begin;
if (begin >= 0) {
while (startstop != 0) {
cout << "enter any number, or press Q to process." << endl;
int oldnum = 0;
int userinput=0;
int newnum = userinput;
int greatestnum = 0;
int greatestcounter = 0;
cin >> userinput;
int x;
bool is_prime = true;
if (userinput == 0 || userinput == 1) {
is_prime = false;
}
// loop to check if n is prime
for (x = 2; x <= userinput / 2; ++x) {
if (userinput % x == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primecounter++;
}
//check if input is greater than previous input
if (greatestnum > userinput) {
greatestnum = userinput;
}
cout << "prime count: " << primecounter << endl;
cout << "greatest num: " << greatestnum << endl;
userinput = 0;
}
return 0;
}
}
greatestnum is only assined if it's greater than the user input. Since it's initialized to 0, the if statement,
if (greatestnum > userinput) {
greatestnum = userinput;
}
will be false unless the user input is less than zero. If you want to make it the greatest from all user inputs, flip it to < and move the int greatestnum = 0; to right above the if (begin >= 0) {.
if (greatestnum < userinput) {
greatestnum = userinput;
}
#include <iostream>
using namespace std;
int main() {
int startstop = 1;
cout << "start program?" << endl;
int begin = 0;
int primecounter = 0,greatestnum = 0,oldnum = 0,userinput = 0;
cin >> begin;
if (begin >= 0) {
while (startstop != 0) {
cout << "enter any number, or press Q to process." << endl;
cin >> userinput;
int x;
bool is_prime = true;
if (userinput == 0 || userinput == 1) {
is_prime = false;
}
// loop to check if n is prime
for (x = 2; x <= userinput / 2; ++x) {
if (userinput % x == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primecounter++;
}
//check if input is greater than previous input
if (userinput > oldnum) {
greatestnum = userinput;
oldnum = userinput;
}
cout << "prime count: " << primecounter << endl;
cout << "greatest num: " << greatestnum << endl;
userinput = 0;
}
return 0;
}
}
Initialize 'oldnum=0' , 'userinput=0' and 'greatestnum=0' outside the loop. And there were some error in logic. If userinput is greater the old num the update greatest num=userinput and oldnum=userinput.

How to use cache in c++?

I have a task to create an application for encoding and decoding using Atbash cipher. I have done the encoding/decoding thing but another part of the task is to cache the already encoded/decoded strings. Cache should be printable with standard stream operators and should be able to be stored and loaded in/from a file. Could someone help me to do it? Thanks in advance! This is my code by now:
#include <iostream>
#include <string>
using namespace std;
string Atbash_cipher(string message)
{
string upperAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string reverseUpperAlpha = "ZYXWVUTSRQPONMLKJIHGFEDCBA";
string lowerAlpha = "abcdefghijklmnopqrstuvwxyz";
string reverseLowerAlpha = "zyxwvutsrqponmlkjihgfedcba";
string cipher = "";
for (int i = 0; i < message.length(); i++)
{
if (message[i] >= 32 && message[i] <= 64 && message[i] >= 173 && message[i] <= 176)
{
cipher += message[i];
}
if (message[i] >= 'A' && message[i] <= 'Z')
{
for (int j = 0; j < upperAlpha.length(); j++) {
if (message[i] == upperAlpha[j])
{
cipher += reverseUpperAlpha[j];
break;
}
}
}
else
{
for (int j = 0; j < lowerAlpha.length(); j++)
{
if (message[i] == lowerAlpha[j])
{
cipher += reverseLowerAlpha[j];
break;
}
}
}
}
return cipher;
}
void menu()
{
int choice;
string message;
do
{
cout << "1. Encrypt message" << endl << "2. Decrypt message" << endl << "0. Exit" <<
endl << "Your choice: ";
cin >> choice;
switch (choice)
{
case 1:
cout << "Enter message to encrypt: ";
cin.ignore();
getline(cin, message);
cout<< Atbash_cipher(message) <<endl;
break;
case 2:
cout << "Enter message to encrypt: ";
cin.ignore();
getline(cin, message);
cout << Atbash_cipher(message) << endl;
break;
}
} while (choice != 0);
}
int main()
{
menu();
return 0;
}

Skipping of For loop while using goto

This is my code for finding a palindrome of a string.
The initial execution works perfectly.
But when it comes to executing the program again, it goes to the label, and skips the cin statement and directly executes everything and finally reaches the end.
This didn't happen when I used it in c++ 6.0, but happens in visual studio 2015
Thanks in advance for your help.
#include "stdafx.h"
#include<iostream>
using namespace std;
void main()
{
char string[100], ch;
int x, i, j, flag = 0;
label:
cout << "Enter a string. Max Length 99 : ";
cin.getline(string, 100);
x = strlen(string);
cout << "Checking For Palindrome...........";
for (long i = 0; i < 5000000; ++i)
{
cout << "";
}
cout << endl;
for (i = 0, j = x - 1; i < x / 2; ++i, --j)
{
if (string[i] == string[j])
continue;
else
{
flag = 1;
break;
}
}
if (flag == 1)
cout << "The String You Entered Is Not A Palindrome";
else
cout << "The String You Entered Is A Palindrome";
cout << "\nDo you want to execute again? (Y/N)";
cin >> ch;
if (ch == 'y' || ch == 'Y')
goto label;
else
cout << "See You Later :)";
}

My initialized variable is displayed empty

My string d is displayed empty (not even a space) on my console, this is getting me confused since I initialized it to "NULL" and I am trying to assign a new value to it which isn't a empty value.
int main(){
string user_String[99];
int user_Input = 0;
cout << "Please insert up to one hundred Strings: ";
cin >> user_Input;
//Check for range
bool check = false;
while( check == false){
if (user_Input < 1 || user_Input >100){
cout << "Please insert up to one hundred Strings: ";
cin >> user_Input;}
else{
check = true;
break;}
}
//User input
cout <<"Please enter string"<< endl;
for (int counter = 0; counter < user_Input; counter++){
int counter2 = counter + 1;
cout << "Enter String " << counter2 << ": ";
cin >> user_String[counter];
}
//Loopig for most letters
string c = "NULL";
for(int counter = 0; counter < user_Input; counter++){
//Making Sure Coun doesn't go out of range
int coun = 0;
if (counter < user_Input){
coun = counter +1;}
else{
coun = counter;
}
string a = user_String[counter];
string b = user_String[coun];
if (a.length() < b.length() && c == "NULL"){
c = b;
}
if(a.length() < b.length() && c!="NULL" && c.length() < b.length()){
c = b;
}
else{
continue;
}
}
cout << "The string "<< c <<" have the most letters." << endl;
//Looping for least letters
string d = "NULL";
for(int counter = 0; counter < user_Input; counter++){
//Making Sure Coun doesn't go out of range
int coun = 0;
if (counter < user_Input){
coun = counter +1;}
else{
coun = counter;
}
string a = user_String[counter];
string b = user_String[coun];
if (a.length() > b.length() && d == "NULL"){
d = b;
}
if(a.length() > b.length() && d!="NULL" && d.length() > b.length()){
d = b;
}
else{
continue;
}
}
cout << "The string " << d <<" have the least letters." << endl;
system("pause");
return 0;
}
You allow the user to enter up to 100 strings, but your array can only hold up to 99 strings. If they actually enter 100 strings, the last string will corrupt memory, assume your code does not crash altogether.
Also, your letters loops have some faulty logic in them. if (counter < user_Input) will always be true, so coun will always be counter+1 and thus exceed the bounds of the array when counter reaches the end of the array. Also, your loops are unnecessarily complex for what they are trying to do.
Try this instead:
int main()
{
string user_String[100];
int user_Input;
do
{
cout << "Please enter the number of Strings (1-100): ";
if (cin >> user_Input)
{
if ((user_Input >= 1) && (user_Input <= 100))
break;
}
else
cin.clear();
}
while (true);
for (int counter = 0; counter < user_Input; ++counter)
{
cout << "Enter String " << counter + 1 << ": ";
cin >> user_String[counter];
}
string b = user_String[0];
for(int counter = 1; counter < user_Input; ++counter)
{
string a = user_String[counter];
if (a.length() > b.length())
b = a;
}
cout << "The string " << b << " has the most letters." << endl;
b = user_String[0];
for(int counter = 1; counter < user_Input; ++counter)
{
string a = user_String[counter];
if (a.length() < b.length())
b = a;
}
cout << "The string " << b <<" has the least letters." << endl;
system("pause");
return 0;
}
With that said, you can get rid of the array altogether and merge the loops together:
int main()
{
string user_String;
int user_Input;
do
{
cout << "Please enter the number of Strings: ";
if (cin >> user_Input)
{
if (user_Input >= 1)
break;
}
else
cin.clear();
}
while (true);
string fewestLetters, mostLetters;
for (int counter = 1; counter <= user_Input; ++counter)
{
cout << "Enter String " << counter << ": ";
cin >> user_String;
if (counter == 1)
{
mostLetters = user_String;
fewestLetters = user_String;
}
else
{
if (user_String.length() > mostLetters.length())
mostLetters = user_String;
if (user_String.length() < fewestLetters.length())
fewestLetters = user_String;
}
}
cout << "The string " << mostLetters << " has the most letters." << endl;
cout << "The string " << fewestLetters << " has the least letters." << endl;
system("pause");
return 0;
}

Replay tic tac toe game

So I am trying to program a way to replay a tic tac toe game after someone wins, loses, or ties.
So basically my attempt to get replay to work, doesnt work. If player 1 won and I type 1 to replay, it would ask player 2 for their input.
Pseudocode outline:
do {
set entire 2d array to '*'
do {
player 1 input
does game tie?
does player 1 win
player 2 input
does game tie?
does player 2 win
} while no one wins
} while replay = 1
My actual code:
//tie check, replay, use pointer notation
#include <iostream>
using namespace std;
void initialize(char [][3]);
void player1(char [][3]);
void player2(char [][3]);
void display(char [][3]);
char check(char [3][3]);
int checkWin(int);
int tie(int);
int askReplay();
int main()
{
char board[3][3];
char end = '*';
int row1, column1, row2,column2;
int replay = 0;
int turns = 0;
//replay loop
do {
//set board to *
initialize(board);
display(board);
do {
//player 1 turn
player1(board);
turns++;
display(board);
//if turns = 9 then tie
replay = tie(turns);
//check if player 1 won
end = check(board);
replay = checkWin(end);
//player 2 turn
player2(board);
turns++;
display(board);
//if turns = 9 then tie
replay = tie(turns);
//check if player 2 won
end = check(board);
replay = checkWin(end);
} while (end == '*');
} while (replay == 1);
return 0;
}
void initialize(char (*array)[3])
{
for (int i = 0;i < 3;i++)
for (int j = 0;j < 3;j++)
array[i][j] = '*';
cout << "New Game\n";
}
void player1(char (*array)[3])
{
int row1, column1;
cout << "Player 1\nRow: ";
cin >> row1;
while (row1 < 0 || row1 > 2) {
cout << "Enter a number between 0 and 2 for Row:: ";
cin >> row1;
}
cout << "Column: ";
cin >> column1;
while (column1 < 0 || column1 > 2) {
cout << "Enter a number between 0 and 2 for Column: ";
cin >> column1;
}
if (array[row1][column1] == '*')
array[row1][column1] = 'X';
else {
cout << "Space Occupied\n";
player1(array);
}
}
void player2(char (*array)[3])
{
int row2,column2;
cout << "Player 2\nRow: ";
cin >> row2;
while (row2 < 0 || row2 > 2) {
cout << "Enter a number between 0 and 2 for Row: ";
cin >> row2;
}
cout << "Column: ";
cin >> column2;
while (column2 < 0 || column2 > 2) {
cout << "Enter a number between 0 and 2 for Column: ";
cin >> column2;
}
if (array[row2][column2] == '*')
array[row2][column2] = 'O';
else {
cout << "Space Occupied\n";
player2(array);
}
}
void display(char (*array)[3])
{
for (int x = 0;x < 3;x++) {
for (int y = 0;y < 3;y++)
cout << *(*(array + x) + y) << " ";
cout << endl;
}
}
char check(char (*array)[3])
{
int i;
/* check rows */
for(i = 0; i < 3; i++)
if(array[i][0] == array[i][1] && array[i][0] == array[i][2])
return array[i][0];
/* check columns */
for(i = 0; i < 3; i++)
if(array[0][i] == array[1][i] && array[0][i] == array[2][i])
return array[0][i];
/* test diagonals */
if(array[0][0] == array[1][1] && array[1][1] == array[2][2])
return array[0][0];
if(array[0][2] == array[1][1] && array[1][1] == array[2][0])
return array[0][2];
return '*';
}
int checkWin(int over)
{
if (over == '*')
return 0;
if (over == 'X')
cout << "Player 1 Won!\n";
else if (over == 'O')
cout << "Player 2 Won!\n";
//ask if they want to play again
int answer;
answer = askReplay();
switch (answer) {
case 1:
return 1;
case 2:
cout << "Thank you for playing.\n";
exit(0);
}
}
int tie(int count)
{
if (count == 9) {
int answer;
cout << "Tie game";
answer = askReplay();
switch (answer) {
case 1:
return 1;
case 2:
cout << "Thank you for playing.\n";
exit(0);
}
}
}
int askReplay()
{
int input;
do {
cout << "Play Again?\n1.Yes\n2.No\nEnter 1 or 2: ";
cin >> input;
if (input > 2 || input < 1)
cout << "Invalid Option\n";
} while(input > 2 || input < 1);
return input;
}
It sounds like you're having troubles with your main loop.
I'd suggest making a variable that controls which player is running and just toggle that.
do
{
set entire 2d array to '*'
current player = 0
do
{
(current player + 1) input
does game tie?
does (current player + 1) win
current player = (current player + 1) % 2
}while no one wins
}while replay = 1
See if that gets you further along.
You may want to look up the Memento Design Pattern.