If Statement not working, input unrecognised (C++) - c++

My program runs without issues, compiles no errors.
The aim of my if statement is to choose if letters are shifted left/right which I have tried to achieve with an if statement leading to 2 functions, however no matter the input from cin >> z; it will always utilize CipherR. Can anyone help me figure this out?
//Start of Document
#include <WinUser.h> //Gives access to windows form library
#include "StdAfx.h" //Standard prefix for vb to save
#include <iostream> //Enables I/O stream cin/cout
#include <string> //Ensures that string data can be assigned
#include <Windows.h> //Gives access to windows library Included libraries, above <winuser.h>
using namespace std;
//Variables
char cipherR(char);
char cipherL(char);
int y;
const string LEFT = "1";
const string RIGHT = "0";
//Main Code
int main()
{
string input; //Declares string variable for temp storage
//MessageBox
int WinUserMessageBox(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType); //defines MessageBox parameters
const int message = MessageBox(NULL, L"Is your location secure?", L"Warning", MB_YESNOCANCEL); //sets up listener for messagebox response
//Switch Response
switch (message) //Initialise case study
{
case IDYES: //Runs this if Yes is selected
//cipher code block
do {
cout << "Enter text to be ciphered/deciphered." << endl;
cout << "Enter blank line to quit." << endl;
getline(cin, input); //Prompts for User Input, stores into temporary var
string output = ""; //Checks for blank input
cout << "Shift Left(1) or Right(0)? \n";
string z; //L or R definer
std::cin >> z;
cout << "Enter number to shift\n";
cin >> y;
if (z == LEFT)
{
for (int x = 0; x < input.length(); x++) // Loops until string.length is reached.
{
output += cipherR(input[x]);
}
} //Adds the value of expression to the value of a variable and assigns the result to the variable.
else if (z == RIGHT)
{
for (int x = 0; x < input.length(); x++) // Loops until string.length is reached.
{
output += cipherL(input[x]); //Adds the value of expression to the value of a variable and assigns the result to the variable.
}
};
cout << output << endl; // If input is blank will end process
} while (!input.length() == 0); //Loops while input.length is NOT equal to 0
break;
//alternate message responses
case IDNO: //Runs this if No is selected
MessageBox(NULL, L"Agents are converging on your location now.", L"Run!", NULL);
return 0;
break;
case IDCANCEL: //Runs this if cancel is selected
MessageBox(NULL, L"Why open this is you're gonna back out?", L"Alert", NULL);
return 0;
break;
}
}
//functions
char cipherR(char c) //function caesar, called into main
{
if (isalpha(c)) //checks if is part of the alphabet
{
c = toupper(c); //ignores casing of input for universal input
c = (((c - 65) + y) % 26) + 65; //performs caesar cipher with algebraic equation
return c; //returns encrypted data
}
if (!isalpha(c)) //if is not alphabetic will make blank
{
return 0; //returns blank
}
// if c isn't alpha, just send it back
}
char cipherL(char c) //function caesar, called into main
{
cout << "This Is left";
if (isalpha(c)) //checks if is part of the alphabet
{
c = toupper(c); //ignores casing of input for universal input
c = (((c - 65) - y) % 26) + 65; //performs caesar cipher with algebraic equation
return c; //returns encrypted data
}
if (!isalpha(c)) //if is not alphabetic will make blank
{
return 0; //returns blank
}
// if c isn't alpha, just send it back
}
//end of sheet

I believe you have your functions swaped. In
if (z == LEFT)
{
for (int x = 0; x < input.length(); x++) // Loops until string.length is reached.
{
output += cipherR(input[x]);
}
} //Adds the value of expression to the value of a variable and assigns the result to the variable.
else if (z == RIGHT)
{
for (int x = 0; x < input.length(); x++) // Loops until string.length is reached.
{
output += cipherL(input[x]); //Adds the value of expression to the value of a variable and assigns the result to the variable.
}
};
When you go into the "left" if statement you are calling cipherR() when you should be calling cipherL(). You also need to fix "right" as you are calling cipherL(). Fixed version:
if (z == LEFT)
{
for (int x = 0; x < input.length(); x++) // Loops until string.length is reached.
{
output += cipherL(input[x]);
// ^ L here
}
} //Adds the value of expression to the value of a variable and assigns the result to the variable.
else if (z == RIGHT)
{
for (int x = 0; x < input.length(); x++) // Loops until string.length is reached.
{
output += cipherR(input[x]); //Adds the value of expression to the value of a variable and assigns the result to the variable.
// ^ R here
}
};

It looks like you think -1 % 26 is 25.
It's not - it's either 1 or -1, depending on the implementation.
In your implementation, it's apparently positive since you get the same result for both shifts.
You can't use the modulus for the left shift.
Instead, use repeated addition:
c = c - y;
while (c < 'A')
{
c += 26;
}
You also want to look over which function you're calling for each case, as you have them switched around.

Related

How can I find prime reversed numbers?

I have to write a program to check if the entered number has these qualifications:
A number that is prime it self, the reverse of that number is also prime, and the number's digits are prime numbers too (Like this number: 7523).
If the needs meet, it has to show "yes" when you enter and run the program otherwise "no".
I know both codes for prime and reverse numbers but I don't know how to merge them.
This is the code:
#include <iostream>
#include <conio.h>
using namespace std;
void prime_check(int x) {
int a, i, flag = 1;
cin >> a;
for (i = 2; i <= a / 2 && flag == 1; i++) {
if (a % i == 0)
flag = 0;
}
if (flag == 1)
cout << "prime";
else
break;
}
int main() {
int a, r, sum = 0;
cin >> a;
while (a != 0) {
r = a % 10;
sum = (sum * 10) + r;
a = a / 10;
}
}
The program has to check each digit of the number entered to see if it is prime or not in every step, then show "yes", but it doesn't work.
Welcome to the site.
I don't know how to merge them.
void prime_check(int n) { /*code*/ }
I'd understand that you don't know how to use this.
It's very easy!
int main()
{
int i = 0;
prime_check(i);
}
If you are confused about how the program executes, you could use a debugger to see where it goes. But since using a debugger can be a bit hard at first, I would suggest to add debug prints to see how the program executes.
This line of code prints the file and line number automatically.
std::cout << __FILE__ << ":" << __LINE__ << "\n";
I'd suggest to add it at the start of every function you wish to understand.
One step further is to make it into a macro, just so that it's easy to use.
#define DEBUGPRINT std::cout << __FILE__ << ":" << __LINE__ << "\n";
Check a working example here:
http://www.cpp.sh/2hpam
Note that it says <stdin>::14 instead of the filename because it's running on a webpage.
I have done some changes to your code, and added comments everywhere I've made changes. Check it out:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0, original; // added original variable, to store the number added
bool eachDigit = true; // added to keep track of each digit
cin >> a;
original = a;
while (a != 0) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && prime_check(original) && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
For optimization, you can check if the entered number is prime or not before starting that loop, and also you can break the loop right away if one of the digits of the entered number is not prime, Like this:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0;
bool eachDigit = true, entered; // added to keep track of each digit
cin >> a;
entered = prime_check(a);
while (a != 0 && entered && eachDigit) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && entered && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
Suppose you have an int variable num which you want to check for your conditions, you can achieve your target by the following:
int rev_num = 0;
bool flag = true; // Assuming 'num' satisfies your conditions, until proven otherwise
if (prime_check(num) == false) {
flag = false;
}
else while (num != 0) {
int digit = num % 10;
rev_num = rev_num * 10 + digit;
// Assuming your prime_check function returns 'true' and 'false'
if (prime_check(digit) == false) {
flag = false;
break;
}
num /= 10;
}
if (prime_check(rev_num) == false) {
flag = false;
}
if (flag) {
cout << "Number satisfies all conditions\n";
}
else {
cout << "Number does not satisfy all conditions\n";
}
The problem is that each of your functions is doing three things, 1) inputting the number, 2) testing the number and 3) outputting the result. To combine these functions you need to have two functions that are only testing the number. Then you can use both functions on the same number, instead of inputting two different numbers and printing two different results. You will need to use function parameters, to pass the input number to the two functions, and function return values to return the result of the test. The inputting of the number and the outputting of the result go in main. Here's an outline
// returns true if the number is a prime, false otherwise
bool prime_check(int a)
{
...
}
// returns true if the number is a reverse prime, false otherwise
bool reverse_prime_check(int a)
{
...
}
int main()
{
int a;
cin >> a;
if (prime_check(a) && reverse_prime_check(a))
cout << "prime\n";
else
cout << "not prime\n";
}
I'll leave you to write the functions themselves, and there's nothing here to do the digit checks either. I'll leave you do to that.

Trying to compare a randomly generated array to user filled array

I am currently working on a project to create a game of Mastermind. The user must input 3 colors and the program will compare which are the correct color and in the proper place,which are the correct color but in the wrong place, and which are the wrong color. All seems well except I'm unable to properly compare the info within the randomly generated array with the user filled array. I'm sure I'd have to use a loop to accomplish this.
-Things that I feel may be the issue:
*The information within both arrays are not being stored properly.
*conflicting types.
void gameS() {
int close, right, attempts = 0;
string choice[3],code; // holds user input
const int arrySize = 5;
srand(time(0)); //random numbers
string ranColor[arrySize] = { "R", "B", "W", "Y", "G" }; // possible color options
for (int i = 0; i < arrySize - 2; i++) //generat random colors
{
int rcolor = rand() % arrySize;
code = ranColor[rcolor];
cout << code << endl;
}
while (attempts < 10) {
cout << "You should input your color choices below. Your options are - R : Red, B : Blue, W : White, Y : Yellow, G : Green.\n" << "Please choose 3 for your " << attempts+1 << " attempt.\n" << "******************************************************\n\n";
cout << "\n\nPlease enter the color of the first peg: "; //user input to choice array spot : 1
cin >> choice[0];
cout << "\nPlease enter the color of the second peg: "; //user input to choice array spot : 2
cin >> choice[1];
cout << "\nPlease enter the color of the third peg: "; //user input to choice array spot : 3
cin >> choice[2];
attempts++; // proceeds to next turn/attempt
//checks for correct colors in correct places
for (int i = 0; i < 3; i++)
{
if (code == choice[i])
{
right++;
choice[i] = "X";
}
}
//Determin the number of right colors in the wrong place
for (int i = 0; i < 3; i++)
{
for (int y = 0; y < 3; y++) {
if (code[i] == choice[y]) {
close++;
choice[i] = "Y";
}
}
}
}
}
I receive errors for the following lines:
*'argument':conversion from tim_t to unsigned in' possible loss of data
srand(time(0));
*Using uninitialized memory 'right'
`if (code == choice[i])
{
right++;
choice[i] = "X";
}`
*Using uninitialized memory 'close'
`for (int i = 0; i < 3; i++)
{
for (int y = 0; y < 3; y++) {
if (code == choice[y])
{
close++;
choice[i] = "Y";
}
}
}
*no operator "==" matches these operands.
*Binary '==':o global operator found which takes type 'std::string'(or there is no acceptable conversion)
`for (int y = 0; y < 3; y++) {
if (code[i] == choice[y])
{
close++;
choice[i] = "Y";
}`
Any tips would be appreciated.
From what I can see there is some initialization problems.
First
int close, right, attempts = 0;
Will leave close and right empty, simply initialize them properly
int close = 0, right = 0, attempts = 0;
It looks like you want to use code as an array, but the problem is, it is not initialized as an array
string choice[3],code; // holds user input
A quick fix is
string choice[3],code[3]; // holds user input
Now, where you generate the answer, there is another syntax problem
code = ranColor[rcolor];
since you want to store the answer in the code array, an index must be specified, in this case
code[i] = ranColor[rcolor];
The final problem lies in
//checks for correct colors in correct places
for (int i = 0; i < 3; i++)
{
if (code == choice[i])
{
right++;
choice[i] = "X";
}
}
Since code is an array now, simply change the condition statement to
if (code[i] == choice[i])

C++ check If a hexadecimal consists of ABCDEF1 OR 0

I have written a program below that converts a string to an int and then converts the decimal number to hexadecimal. I'm struggling to check if the hexadecimal consists only of these characters A, B, C, D, E, F, 1, 0. If so set a flag to true or false.
#include<iostream>
#include <stdlib.h>
#include <string>
#include <sstream>
string solution(string &S){
int n = stoi(S);
int answer;
cout << "stoi(\"" << S << "\") is "
<< n << '\n';
//decToHexa(myint);
// char array to store hexadecimal number
string hexaDeciNum[100];
// counter for hexadecimal number array
int i = 0;
while(n!=0)
{
// temporary variable to store remainder
int temp = 0;
// storing remainder in temp variable.
temp = n % 16;
// check if temp < 10
if(temp < 10)
{
hexaDeciNum[i] = temp + 48;
i++;
}
else
{
hexaDeciNum[i] = temp + 55;
i++;
}
n = n/16;
}
// printing hexadecimal number array in reverse order
for(int j=i-1; j>=0; j--){
cout << hexaDeciNum[j] << "\n";
return "";
}
int main() {
string word = "300";
cout << solution(word);
return 0;
}
OK, it is not the exact answer to what you are asking for, but it is a valuable alternative approach for the entire problem of conversion:
char letter(unsigned int digit)
{
return "0123456789abcdefg"[digit];
// alternatively upper case letters, if you prefer...
}
Now you don't have to differenciate... You can even use this approach for inverse conversion:
int digit(char letter)
{
int d = -1; // invalid letter...
char const* letters = "0123456789abcdefABCDEF";
char* l = strchr(letters, letter);
if(l)
{
d = l - letters;
if(d >= 16)
d -= 6;
}
// alternatively upper case letters, if you prefer...
}
Another advantage: This works even on these strange character sets where digits and letters are not necessarily grouped into ranges (e. g. EBCDIC).

C++ : How do I only look at one dimension of a 2-Dimensional array?

I'm writing a battleship game in the console, and I'm writing a function that will draw one grid based on a 2-dimensional array. The approach I'm taking is such:
--> Draw 1 row which contains a character X amount of times (like 10)
--> Draw that row, putting a newline at the end of the drawing process, 10 times to get a nice field.
Now, I do need to insert a newline at the end of 1 row, right? But how do I compare only the x-element of the array, and not the y-element?
Here's my code:
// Includes
#include <iostream> // For IO
#include <cstdlib> // For rand()
// Important game stuff
const int empty = 0; // Water
const int occupied = 1; // Ship
const int hit = 2; // Hit a ship
const int missed = 3; // Missed
// Variables
const int fields = 10;
// We want a 10x10 field
int board[fields][fields]; // board[x][y]
// Initialize board
void initb(int array[fields][fields]);
// Draw board x-axis
void drawbx(int array[fields][fields]);
int main(void)
{
drawbx(board;)
// game(Players);
return 0;
}
// Initialize the board, make everything hit
void initb(int array[fields][fields])
{
for(int x = 1; x <= 10; x++)
{
for(int y = 1; y <= 10; y++)
{
array[x][y] = hit;
}
}
}
void drawbx(int array[fields][fields])
{
for(int i = 1; i <= fields; i++)
{
if(array[i][] == empty || array[i][] == occupied)
{
if(i == 10)
std::cout << " X\n";
else if(i == 1)
std::cout << "X ";
else
std::cout << " X ";
}
}
}
Take a look specifically at the drawbx() function. I want to draw something like
X X X X X X X X X X\n
The syntax that I tried, if(array[i][] == empty || array[i][] == occupied), doesn't work. There must be an expression in the second pair of square brackets. Can someone help me?
I see two major problems:
1) Array indexing is out of range. You use index 1 to 10. It shall be 0 to 9.
2) Code array[i][] == empty is illegal syntax. You can't leave one index empty.
If you want a function that draw one row, perhaps pass the row number to the function like:
void draw_one_row(int array[fields][fields], int row_to_draw)
{
for(int i = 0; i < fields; i++)
{
if(array[row_to_draw][i] == empty || array[row_to_draw][i] == occupied)
{
...
}
}
}
To draw the whole board:
void draw_board(int array[fields][fields])
{
for(int i = 0; i < fields; i++)
{
draw_one_row(array, i);
}
}
BTW: Since you write C++, I'll recommend that you use vector instead of arrays.

c++ binary to decimal converter input to only accept 1 or 0

Hello I am trying to do a programming assignment that converts a binary number to a decimal. The problem states that I have to get the users input as a sting and if there is anything other than a 1 or a 0 in the users input it should give an error message then prompt them to give a new input. I have been trying for a while now and I cant seem to get it right can anyone help me?
so far this is my best attempt it will run every input of the string into a if statement but it only seems to care about the last digit i cant think of a way to make it so if there is a single error it will keep while loop statement as true to keep going.
#include <iostream>
#include <string>
using namespace std;
string a;
int input();
int main()
{
input();
int stop;
cin >> stop;
return 0;
}
int input()
{
int x, count, repeat = 0;
while (repeat == 0)
{
cout << "Enter a string representing a binary number => ";
cin >> a;
count = a.length();
for (x = 0; x < count; x++)
{
if (a[x] >= '0' &&a[x] <= '1')
{
repeat = 1;
}
else
repeat = 0;
}
}
return 0;
}
return 0;
}
Change your for loop as this:
count = a.length();
repeat = 1;
for (x = 0; x < count; x++)
{
if (a[x] != '0' && a[x] != '1')
{
repeat = 0;
break;
}
}
The idea is that repeat is assumed to be 1 at first (so you assume that your input is valid). Later on, if any of your input characters is not a 0 or 1, then you set repeat to 0 and exit the loop (there's no need to keep looking for another character)