I think there's some problem in my vs code I am new to this coding stuff even after writing the correct code it gives me wrong results in almost every second code I write i get uncertain results Plz guys help me with this , plz check running this code in your machine....
#include <iostream>
using namespace std;
int main()
{
char a[30];
cout << "enter the hexadecimal";
cin >> a;
int i = 0, c, digit, decimal = 0, p = 1;
while (a[i] != '\0') {
i++;
}
for (int j = i; j >= 0; j--) {
c = a[j];
if (c >= 48 && c <= 57) {
digit = c - 48;
}
else if (c >= 97 && c <= 112) {
digit = c - 87;
}
decimal += digit * p;
p *= 8;
}
cout << "\ndecimal is " << decimal;
return 0;
}
while entering hexa decimal plz only enter small alphabets i have not taken capital letters into consideration
for cheking hexadecimal to decimal use this site https://www.rapidtables.com/convert/number/hex-to-decimal.html?x=146
There are several problems with the code, but I think that the main one is that you are multiplying p by 8 when it should be 16 (as hex is base-16, not base-8).
You also should take care with invalid inputs. What happens if someone enters an invalid letter 'j' for instance?
Besides, when you calculate the initial length of the string, you are setting ito the position of the array with a '\0' value so when you start processing the input, a[i] is 0 and that leads to using an uninitialized variable (digit has not been assigned a value, this is related to the previous "invalid input" issue).
By the way, I would also use chars in the comparisions instead of ASCII codes, it's easier to see what you are looking for:
if (c >= '0' && c <= '9') {
digit = c - '0';
}
and so on...
Task: This cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet.
For example:
string = "Abc Def Ghi 999 -*%/&()[]"
shift(number that you entered) = 1(Can be any integer)
Program should print like this: Bcd Efg Hij -*%/&()[]
I did this with a void function but once I tried to do same thing with string function it didn't work. It just process first element of string then returns the value. For this particular situation
my program prints like "Bbc Def Ghi 999 -*%/&()[]"
Any idea to solve this problem?
#include <iostream>
#include <cmath>
using namespace std;
string Cipher(string password, int shift) {
char Uppercase[26] = { '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' };
char Lowercase[26] = { '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' };
for (int i = 0; i < password.length(); i++) {
for (int k = 0; k < 26; k++) {
int add = shift + k;
if (password[i] == Uppercase[k]) {
for (int i = 0; add > 25; i++) { // controlling add isn't bigger than 25
add -= 25;
}
password[i] = Uppercase[add]; // converting each letter
}
else if (password[i] == Lowercase[k]) {
for (int i = 0; add > 25; i++) { // controlling add isn't bigger than 25
add -= 25;
}
password[i] = Lowercase[add]; //converting each letter
}
else {
k = 25; // if element of string is different from letters, program goes to next element
}
}
}
return password;
}
int main() {
cout << "Please enter an integer different from 0 and multiples of 25: ";
string password = "Abc def ghi 999 -*%/&()[]";
int shift;
cin >> shift;
cout<< Cipher(password, shift);
system("pause>0");
}
Your encryption problem can be solved with one statement by using modern C++.
But because this is somehow advanced, I will give a detailed explanation.
Let us first think, what to do and then, how to implement.
The what:
Only alpha characters shall be converted
None alpha characters shall be output unencrypted (same as input)
In case of encryption, the case of the original letter shall be preserved for the encrypted letter. Meaning, if at position 5 was an uppcase letter, also in the encrypted string the letter in position 5 shall be uppercase
Letters shall be shifted by a specified amount.
The how:
We will first check, it the original letter is an alpha-letter by using the isalpha-function.
So, for the case that it is an alpha letter, we will check, if the letter is in uppercase or in lowercase. Actually, we check only, if it is a uppercase letter.
Because if it is not, then it must be a lowercase letter (because it was definitely a letter, what we did check before, and, if it is not upper, then it is lower case). For this check, we use the isupper-function.
We will then do the shift action. And convert back to a letter, taken the case into account.
We assume ASCII. If we to convert an ASCII letter/character into a 0 based index, we need to do the following:
If we look in the ASCII table, then we see, that and 'A' is equivalent to 65 and so forth. So, to get the 0-based index, we subtract 65 from the letter. Then we have an index value between 0 and 25.
Then we add the shift value. There could of course be an overflow. But, this can be simply corrected by a modulo 26 division.
So: 26->0, 27->1, 28->2 and so on. Rather simple. But, because we want to have later a letter again, we will add 65 to this result.
For lowercase letters, we will do nearly the same, but use 97 for the offset to letter 'a'.
Then, we can put verything in one expresion by using the ternary or conditional-operator.
std::isalpha(c) ? std::isupper(c) ? (c - 65 + shift) % 26 + 65 : (c - 97 + shift) % 26 + 97 : c
This is a short for
// Check if letter/character is alpha
if (std::isalpha(c)) {
// Now check for upper or lower case
if (std::isupper(c)) {
// The character is uppercase
c = (c - 65 + shift) % 26 + 65;
}
else {
// The character is lower case
c = (c - 97 + shift) % 26 + 97;
}
}
else {
// The character is not alpha
}
Same as the one liner, no difference
So, first, check for alpha. If true, check for uppercase, if true, do the conversion for uppcase letter, else for lower case letters. If it was no alpha letter, then leave it unchanged.
All this we will then embed as a Lambda-expresion in a std::transform-statement. Please see here for a description.
The result will be one statement only, for the whole conversion process:
std::transform(password.begin(), password.end(), password.begin(), [shift](const char c)
{return std::isalpha(c) ? std::isupper(c) ? (c - 65 + shift) % 26 + 65 : (c - 97 + shift) % 26 + 97 : c; });
At the end, we build a small driver program for demo purposes:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
// Our password
std::string password = "Abc def ghi 999 -*%/&()[]";
// Give instruction to the user
std::cout << "\nPlease enter a postive integer: ";
// Get number of shifts from user and check, if the value could be read
if (int shift{}; std::cin >> shift && shift > 0) {
// Now do the encryption
std::transform(password.begin(), password.end(), password.begin(), [shift](const char c)
{return std::isalpha(c) ? std::isupper(c) ? (c - 65 + shift) % 26 + 65 : (c - 97 + shift) % 26 + 97 : c; });
// Show the result to the user
std::cout << "\n\nEncrypted passphrase: \t" << password << '\n';
}
else std::cerr << "\n\n*** Error: Problem with input!\n\n";
return 0;
}
And, since the one liner is maybe too advanced, let's use the explicit and more verbose code. Just to be complete:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
int main() {
// Our password
std::string password = "Abc def ghi 999 -*%/&()[]";
// Give instruction to the user
std::cout << "\nPlease enter a postive integer: ";
// Get number of shifts from user and check, if the value could be read
if (int shift{}; std::cin >> shift && shift > 0) {
// --------------Can be written in one statement -----------------------
for (char& c : password) {
// Check if letter/character is alpha
if (std::isalpha(c)) {
// Now check for upper or lower case
if (std::isupper(c)) {
// The character is uppercase
c = (c - 65 + shift) % 26 + 65;
}
else {
// The character is lower case
c = (c - 97 + shift) % 26 + 97;
}
}
else {
// The character is not alpha
}
// ------------------------------------------------------------------
}
// Show the result to the user
std::cout << "\n\nEncrypted passphrase: \t" << password << '\n';
}
else std::cerr << "\n\n*** Error: Problem with input!\n\n";
return 0;
}
Within your k loop you determine the index of the letter in the alphabet. However, when e.g. i=1 then password[1] represents the letter 'b'. Now, starting the k-loop from k==0 where Uppercase[0] and Lowercase[0] represent 'A' and 'a', respectively, you directly end up in the else condition and your k-loop terminates without doing anything (you set k=25 and increment it). Here is a fixed version (note that I also use the modulo operator % to make sure that 0 < add < 26:
#include <iostream>
#include <cmath>
using namespace std;
string Cipher(string password, int shift) {
char Uppercase[26] = { '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' };
char Lowercase[26] = { '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' };
for (int i = 0; i < password.length(); i++) {
for (int k = 0; k < 26; k++) {
int add = (shift + k)%26;
if (password[i] == Uppercase[k]) {
password[i] = Uppercase[add]; // converting each letter
break;
}
else if (password[i] == Lowercase[k]) {
password[i] = Lowercase[add]; //converting each letter
break;
}
}
}
return password;
}
int main() {
cout << "Please enter an integer different from 0 and multiples of 25: ";
string password = "Abc def ghi 999 -*%/&()[]";
int shift;
cin >> shift;
cout<< Cipher(password, shift);
system("pause>0");
}
So let's say we have the following case: for ”12323465723” possible answers would be ”abcbcdfegbc” (1 2 3 2 3 4 6 5 7 2 3), ”awwdfegw” (1 23 23 4 6 5 7 23), ”lcwdefgw” (12 3 23 4 6 5 7 23), in this case, the user will input numbers from 1 to 26, not divided by any space and the program itself will suggest 3 ways of interpreting the numbers, getting the most of the combinations from 1 to 26 these being the values from a to z
As you can see this is edited, as this is the last part of the problem, Thank you all who have helped me this far, I've managed to solve half of my problem, only the above mentioned one is left.
SOLVED -> Thank you
This involves a decision between 0 to 2 outcomes at each step. The base cases are there are no more characters or none of them can be used. In the latter case, we backtrack to output the entire tree. We store the word in memory like dynamic programming. This naturally leads to a recursive algorithm.
#include <stdlib.h> /* EXIT */
#include <stdio.h> /* (f)printf */
#include <errno.h> /* errno */
#include <string.h> /* strlen */
static char word[2000];
static size_t count;
static void recurse(const char *const str) {
/* Base case when it hits the end of the string. */
if(*str == '\0') { printf("%.*s\n", (int)count, word); return; }
/* Bad input. */
if(*str < '0' || *str > '9') { errno = ERANGE; return; }
/* Zero is not a valid start; backtrack without output. */
if(*str == '0') return;
/* Recurse with one digit. */
word[count++] = *str - '0' + 'a' - 1;
recurse(str + 1);
count--;
/* Maybe recurse with two digits. */
if((*str != '1' && *str != '2')
|| (*str == '1' && (str[1] < '0' || str[1] > '9'))
|| (*str == '2' && (str[1] < '0' || str[1] > '6'))) return;
word[count++] = (str[0] - '0') * 10 + str[1] - '0' + 'a' - 1;
recurse(str + 2);
count--;
}
int main(int argc, char **argv) {
if(argc != 2)
return fprintf(stderr, "Usage: a.out <number>\n"), EXIT_FAILURE;
if(strlen(argv[1]) > sizeof word)
return fprintf(stderr, "Too long.\n"), EXIT_FAILURE;
recurse(argv[1]);
return errno ? (perror("numbers"), EXIT_FAILURE) : EXIT_SUCCESS;
}
When run on your original input, ./a.out 12323465723, it gives,
abcbcdfegbc
abcbcdfegw
abcwdfegbc
abcwdfegw
awbcdfegbc
awbcdfegw
awwdfegbc
awwdfegw
lcbcdfegbc
lcbcdfegw
lcwdfegbc
lcwdfegw
(I think you have made a transposition in lcwdefgw.)
According to ASCII table we know that from 65 to 90 it A to Z.
so below is the simple logic to achieve what you're trying.
int main(){
int n;
cin>>n;
n=n+64;
char a=(char) n;
if (a>=64 && a<=90)
cout<<a;
else cout<<"Error";
return 0;
}
If you want to count the occurencs of "ab" then this will do it:
int main()
{
char line[150];
int grup = 0;
cout << "Enter a line of string: ";
cin.getline(line, 150);
for (int i = 0; line[i] != '\0'; ++i)
{
if (line[i] == 'a' && line[i+1] == 'b')
{
++grup;
}
}
cout << "Occurences of ab: " << grup << endl;
return 0;
}
If you want to convert an int to an ASCII-value you can do that using this code:
// Output ASCII-values
int nr;
do {
cout << "\nEnter a number: ";
cin >> nr;
nr += 96; // + 96 because the ASCII-values of lower case letters start after 96
cout << (char) nr;
} while (nr > 96 && nr < 123);
Here I use the C style of casting values to keep things simple.
Also bear in mind ASCII-values: ASCII Table
Hope this helps.
This could be an interesting problem and you probably tagged it wrong, There's nothing specific to C++ here, but more on algorithm.
First of all the "decode" method that you described from numerical to alphabetical strings is ambiguious. Eg., 135 could be interpreted as either "ace" or "me". Is this simply an oversight or the intended question?
Suppose the ambiguity is just an oversight, and the user will enter numbers properly separated by say a white space (eg., either "1 3 5" or "13 5"). Let nstr be the numerical string, astr be the alphabetical string to count, then you would
Set i=0, cnt=0.
Read the next integer k from nstr (like in this answer).
Decode k into character ch
If ch == astr[i], increment i
If i == astr.length(), set i=0 and increment cnt
Repeat from 2 until reaching the end of nstr.
On the other hand, suppose the ambiguous decode is intended (the numerical string is supposed to have multiple ways to be decoded), further clarification is needed in order to write a solution. For example, how many k's are there in "1111"? Is it 1 or 2, given "1111" can be decoded either as aka or kk, or maybe even 3, if the counting of k doesn't care about how the entire "1111" is decoded?
i'm trying to implement Ceaser cipher in c++ language
#include <iostream>
#include <string>
#include <locale>
using namespace std;
int main()
{
string word;
getline(cin,word);
for(int i=0; i<word.length();i++)
{
if(isalnum(word[i]))
{
//shift by 3
word[i]+= 3;
}
}
cout << word ;
return 0;
}
what i want is to limit the output also for only letter and number .
for example if i want to shift z by 3 the output would be 'c' and not '}' as in my code .
Compilers are much better at handling the tedious details than humans, so in this case, I would write the code to show clearly what you intend, and then let the compiler figure out the numbers.
For example, if you want to shift a letter, don't you really just want to add 3 to the index of the letter in the range A to Z, and then mod by 26 -- the number of letters from A to Z? This is really what you want -- rotate around the circle of LETTERS from A to Z, of which there are 26, and not worry about ASCII values.
In that case, you can let the compiler figure it out for you:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int shift = 3;
char* input = "Is it 90 with a ZERO?";
printf("%s\n", input);
int length = strlen(input);
char* output = malloc(length + 1);
output[length] = '\0';
for (int i = 0; i < length; i++)
{
char c = input[i];
if (c >= 'A' && c <= 'Z')
{
c = (((c - 'A') + shift) % 26) + 'A';
}
else if (c >= 'a' && c <= 'z')
{
c = (((c - 'a') + shift) % 26) + 'a';
}
else if (c >= '0' && c <= '9')
{
c = (((c - '0') + shift) % 10) + '0';
}
output[i] = c;
}
printf("%s\n", output);
}
Why would you want to take on that responsibility, if you are not worried about speed or memory footprint?
You have to make sure it does not go out of the valid range for ASCII letters. A way of doing this is to convert the input to lowercase, then make sure that when the shift is added, it does not exceed 122 (z's value in ASCII).
if (word[i] + SHIFT > 'z') {
SHIFT -= 123 - word[i];
word[i] = 'a'; // go back to the beginning
word[i] += SHIFT; // add on the remaining amount
}
This should work.This assumes that there will be only lower case letters.
word[i]+= 3;
//at this point word[i] might have cross the ascii limit for lower case letters
ie may be word[i]>122.Ascii range for lower case letters is 97-122
So we use mod to wrap it around.
But now may be word[i]<97 which is again out of range so we add 97 to it.
word[i]%=123;
if(word[i]<97)word[i]+=97;
Example z
word[i]+=3 makes word[i] as 125 //out of range
word[i]%=123 //word[i]=3
word[i]+=97 //word[i]=99=c
#include <iostream>
using namespace std;
Int main() {
cout<<"Give me a letter" <<endl;
char letter;
cin>>letter;
cout<<letter;
(Int)letter;
letter+=2;
cout<<(char)letter;
(Int)letter;
letter-=25;
cout<<(char)letter;
return 0;
}
How would I manipulate the numbers in a way so that the numbers will always output a letter.
ie: if the letter z was chosen and adding 2 is a symbol how would I manipulate it in a way so that it will always stay between the numbers for capital numbers and uncapitalized numbers. Thanks. Please try to keep answers at a beginner level please I am new to this.
if(letter > 'z') {
//do stuff
}
if(letter < 'a' && letter > 'Z') {
//do stuff
}
if(letter < 'A') {
//do stuff
}
It just depends on how you want to handle the character when it goes into one of the three ranges on the ASCII chart in which the characters are not letters.
As a side note, you don't have to cast a char to an int to do math with it.
char myChar = 'a' + 2;
cout << myChar;
This will print: c
c has an ASCII value of 2 more than a.
The surest method is to use a table for each category, and do
your arithmetic on its index, modulo the size of the table.
Thus, for just lower case letters, you might do something like:
char
transcode( char original )
{
char results = original;
static std::string const lower( "abcdefghijklmnopqrstuvwxyz" );
auto pos = std::find( lower.begin(), lower.end(), results );
if ( pos != lower.end() ) {
int index = pos - lower.begin();
index = (index + 2) % lower.size();
results = lower[ index ];
}
return results;
}
This solution is general, and will work regardless of the sets
of letters you want to deal with. For digits (and for upper and
lower case, if you aren't too worried about portability), you
can take advantage of the fact that the code points are
contiguous, and do something like:
char
transcode( char original )
{
char results = original;
if ( results >= '0' && results <= '9' ) {
char tmp = results - '0'
tmp = (tmp + 2) % 10;
results = tmp + '0';
}
return results;
}
An alternative implementation would be to use something like:
results = results + 2;
if ( results > '9' ) {
results -= 10;
}
in the if above. These two solutions are mathematically
equivalent.
This is only guaranteed to work for digits, but will generally
work for upper or lower case if you limit yourself to the
original ASCII character set. (Be aware that most systems today
support extended character sets.)
You can test directly against ASCII chars by using 'x' notation. Further, you can test things together using && ("and" respectively"):
if ('a' <= letter && letter <= 'z') {
// Letter is between 'a' and 'z'
} else if ('A' <= letter && letter <= 'Z')) {
// Letter is between 'A' and 'Z'
} else {
// Error! Letter is not between 'a' and 'z' or 'A' and 'Z'
}
Or you can use the standard library function std::isalpha which handles this for you:
if (std::isalpha(letter)) {
// Letter is between 'a' and 'z' or 'A' and 'Z'
} else {
// Error! Letter is not between 'a' and 'z' or 'A' and 'Z'
}