Hey guys I have a program here that basically needs a key to open encrypted data but for some reason every time I run the program when converting the Ascii numbers to characters I get characters with the wrong Ascii value. For example in the code below if it tried converting the Ascii Value '50' to a char I would get 'e' instead of '2'. Any help would be much appreciated.
#include "stdafx.h"
#include "iostream"
#include "string"
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
string key = "5053525055";
int asciiValues;
char asciiChars;
for (int i = 0; i < key.length(); i += 2)
{
asciiValues = (int)(key[i] + key[i + 1]);
asciiChars = (int)(key[i] + key[i + 1]);
}
Here's the complete code for those interested.
#include "stdafx.h"
#include "iostream"
#include "string"
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
void encryption(string text)
{
char asciiChar;
int asciiValue = 0;
string key;
string encoded;
srand((unsigned)time(0));
int random_integer = rand();
cout << random_integer << endl;
//Creates the key for the string.
for (int i = 0; i < to_string(random_integer).length(); i++)
{
int asciiValue = (char)(to_string(random_integer)[i]);
key = key + to_string(asciiValue);
cout << asciiValue << endl;
}
int help = to_string(asciiValue).length();
/*Function that converts the individual characters in the input
string to AsciiValues and then puts them into the encoded data.*/
for (int i = 0; i < text.length(); i++)
{
int asciiValue = char(text[i]) + random_integer;
encoded = encoded + to_string(asciiValue) + ".";
}
cout << "Encrypted data: " << encoded << endl;
cout << "Your key for this encoded data is " << key << endl;
}
void decryption(string text, string key)
{
char asciiChars;
int asciiValues;
int number;
string qkey;
string decoded;
/*for (int i = 0; i < to_string(random_integer).length(); i++)
{
int asciiValue = (char)(to_string(random_integer)[i]);
key = key + to_string(asciiValue);
cout << asciiValue << endl;
}*/
for (int i = 0; i < key.length(); i += 2)
{
asciiValues = (int)(key[i] + key[i + 1]);
asciiChars = (int)(key[i] + key[i + 1]);
number = asciiChars - '0';
cout << number << endl;
}
cin >> qkey;
}
int main()
{
string answer;
int question = 0;
string vkey;
ask:
cout << "Would you like to:\nEncrypt Data[1]\nDecrypt Data[2]\nExit[3]" <<
endl;
cin >> question;
if (to_string(question) != "1"&&to_string(question) !=
"2"&&to_string(question) != "3")
{
goto ask;
}
else if (to_string(question) == "1")
{
while (answer.length() > 1000 || answer.length() < 1)
{
cout << "Please enter a string that has a length of 1 to 1000
characters. ";
cin >> answer;
cout << endl;
}
encryption(answer);
cin >> answer;
goto ask;
}
else if (to_string(question) == "2")
{
cout << "Please enter the string you would like decrypted. ";
cin >> answer;
cout << endl;
cout << "Now please enter the key for the string. ";
cin >> vkey;
cout << endl;
decryption(answer, vkey);
}
return 0;
}
ASCII number characters begin at 30hex (or 48dec). Therefore '0' = 30hex. So, to get an ASCII character, you must add '0' (30h).
'cout << 5 + '0'; // 53dec (35hex)
Related
This question already has answers here:
Why std::cin string input asking me for each space
(2 answers)
Closed 2 years ago.
I wrote a program that encrypts a string with the Caesar method. I have a problem when I try to enter a password consisting of several words separated by a space. the code itself works but cuts me off at the time of a space in the string
i tried to add some ifs but it didn't have any effect, so it only shows working code
#include <fstream>
#include <cstdlib>
#include <string>
#include <conio.h>
using namespace std;
int main() {
string wynik = "";
int i,przesu;
system("cls");
cout << "how many shift a password" << endl;
cin >> przesu;
cout << "your password to encode: ";
cin >> wynik;
for (i = 0; i < wynik.length(); i++) {
if ((int)wynik[i] == 32 ) {
wynik[i] = wynik[i];
}
else {
wynik[i] = toupper(wynik[i]);
}
}
for (i = 0; i < wynik.length(); i++) {
if (isupper(wynik[i])) {
wynik[i] = wynik[i] + przesu;
if (wynik[i] > 90) {
wynik[i] = wynik[i] - 26;
}
}
else {
wynik[i] += wynik[i];
}
}
cout << endl << "your encode password: " << wynik << endl;
cout << "press any button to continue";
_getch();
}
Hi I think that you could use the getline() function for this. It reads the line untill it encounters a delimiter(the end of line character "\n" by default). But you should also use cin.ignore() because without it your getline() function wouldn't work properly.
Here is your code with the getline():
#include <fstream>
#include <cstdlib>
#include <string>
#include <conio.h>
#include <iostream>
using namespace std;
int main() {
string wynik = "";
int i,przesu;
system("cls");
cout << "how many shift a password" << endl;
cin >> przesu;
cin.ignore();
cout << "your password to encode: ";
getline(cin, wynik);
for (i = 0; i < wynik.length(); i++) {
if ((int)wynik[i] == 32 ) {
wynik[i] = wynik[i];
}
else {
wynik[i] = toupper(wynik[i]);
}
}
for (i = 0; i < wynik.length(); i++) {
if(wynik[i] != ' '){
if (isupper(wynik[i])) {
wynik[i] = wynik[i] + przesu;
if (wynik[i] > 90) {
wynik[i] = wynik[i] - 26;
}
}
else {
wynik[i] += wynik[i];
}
}
}
cout << endl << "your encode password: " << wynik << endl;
cout << "press any button to continue";
_getch();
}
I also added another if statement in your second loop. It checks if the character is different than a space because we do not want any random symbols in our output. I hope that I answered your question. Let me know if you want to know anything else.
#include <iostream>
using namespace std;
int main() {
string end_wynik = "",wynik;
int i,przesu;
system("cls");
cout << "how many shift a password" << endl;
cin >> przesu;
cout << "your password to encode: ";
while(cin >> wynik) {
for (i = 0; i < wynik.length(); i++) {
wynik[i] = toupper(wynik[i]);
if (isupper(wynik[i])) {
wynik[i] = wynik[i] + przesu;
if (wynik[i] > 90) {
wynik[i] = wynik[i] - 26;
}
}
else {
wynik[i] += wynik[i];
}
}
end_wynik += wynik + " ";
}
cout << endl << "your encode password: " << end_wynik << endl;
system("pause");
}
Example here IDEONE
I am trying to remove the spaces from a string to validate a Palindrome phrase. I have looked up other methods, but my professor literally copy and pasted the remove space for loop in our instructions but I can't get it to work and he says he doesn't want us going to the internet for help. I am trying to remove spaces from a phrase like "too hot to hoot" to validate it. I can get my program to work with single words like "bob", but not phrases.
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char input[100];
cout << "Please enter a word/phrase: ";
cin >> input;
for (int i = 0; i < strlen(input); i++)
{
while (s[i] == ' ')//getting "s" is undefined error
s.erase(i,1);
}
int i = 0;
int j = strlen(input)-1;
bool a = true;
for (i = 0; i < j; i++)
{
if (input[i] != input[j])
{
a = false;
}
j--;
}
if(a)
{
cout << input << " is a Valid Palindrome." << endl;
}
else
{
cout<< input << " is not a Valid Palindrome." << endl;
}
system("pause");
return 0;
}
Maybe you have not copy the result from temporary variable 's'. So, the modified codes should be:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <cstring>
using namespace std;
int main(int argc, char *argv[])
{
char input[100];
cout << "Please enter a word/phrase: ";
fgets(input, 100, stdin);
string s(input); // define a temporary variable 's'
int i = 0;
while (i < s.length())
{
if (s[i] == ' ' || s[i] == '\n')
{
s.erase(i, 1); // erase from variable 's', other then 'input'
continue;
}
i++;
}
// copy result from 's' to 'input'
sprintf(input, "%s", s.c_str());
int j = strlen(input) - 1;
bool a = true;
i = 0;
for (i = 0; i < j; i++)
{
if (input[i] != input[j])
{
a = false;
}
j--;
}
if (a)
{
cout << input << " is a Valid Palindrome." << endl;
}
else
{
cout << input << " is not a Valid Palindrome." << endl;
}
system("pause");
return 0;
}
I have a string that contains X words (between each word there is a space) I have to move the words in a circular motion to the left according to the number that the user inserts. For example:
"hi my name is aviv and",
the user entered 2. "name is aviv and hi my" I'm looking for legality that repeats itself but I can not find.
Thanks for the guidance. Most importantly, I can not use built-in libraries
Update:
I see there are examples with libraries, I can not use any library.
So what I've done so far.
I wrote a function that gets a string and a number from the user, to move left.
Before sending the string to the function I try to calculate the number of characters I need to move.
My output is - "name is avivhi my"
Regarding the function:
When it gets a string without spaces it works great.
This is my code:
int main()
{
char str[] = "hi my name is aviv";
char str2[] = "hi my name is aviv";
int CountSpace = 0, CountWord = 0;
int Size = 18, flag = 0;
int MoveLeft, Index = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ')
{
CountSpace++;
}
}
CountWord = CountSpace + 1;//Understand how many words there are in a string.
cin >> MoveLeft;
if (MoveLeft >= CountWord)//
{
MoveLeft = (MoveLeft - ((MoveLeft / CountWord) * CountWord));//the size of movment;//To reduce the amount of moves if there is such a possibility
}
for (int i = Size - 1; i >= 0; i--)
{
if (str[i] == ' ')
{
flag++;
}
if (flag == MoveLeft)
{
Index = Size - 1 - (i + 1);//That's the amount of characters I have to move
break;
}
}
MoveLeft = Index;
//This code belongs to the function that accepts a string and the amount to move the characters
for (int i = 0; i < Size; i++)
{
if (i + MoveLeft < Size)
{
str[i] = str2[i + MoveLeft];
}
else
{
str[i] = str2[(i + MoveLeft) - Size];
}
}
cout << "Move Left: " << MoveLeft << endl << str << endl << str2 << endl;
return 0;
}
Here's a hint:
vector<string> words = Your_Code_To_Split_Input_Into_Words();
int count = words.size();
int shift = Your_Code_To_Read_Users_Input();
// print the sentence with the rotation specified by shift
for (int i = 0; i < count; i++)
{
int shifted_index = (i + shift) % count; // modulo math implements circular rotation
string spacing = (i == 0) ? "" : " "; // add a space before each word, except first word
cout << spacing << words[shifted_index];
}
cout << endl;
One possible answer, i highly recommend using vectors instead of regular arrays, it's easy and more dynamic, but i didn't use it because you said you can't use built-in libraries.
#include <iostream>
#include<string>
using namespace std;
int main() {
string a[10000];
int counter = 0;
string b = "hi my name is aviv and";
string temp = "";
int userNum = 2;
for(int i=0;i<b.length() ; i++){
if(b[i]!=' '){
temp+=b[i];
}
else if(b[i]==' ' && temp.length()){
a[counter]= temp;
temp = "";
counter++;
}
}
if(temp.length()){
a[counter] = temp;
}
for(int i=userNum;i<=counter+userNum;i++){
cout<<a[i%(counter+1)]<<endl;
}
}
If you can make use of std::rotate() from <algorithm>, this is much easy to do with that. Parse the words using std::stringstream and store to std::vector. Then apply the shif directly to the vector.
Sample Output: https://www.ideone.com/rSPhPR
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
int main()
{
std::vector<std::string> vec;
std::string str = "hi my name is aviv and";
std::string word;
std::stringstream sstr(str);
while(std::getline(sstr, word,' '))
vec.emplace_back(word);
int shift;
std::cout << "Enter the Shift: ";
std::cin >> shift;
std::rotate(vec.begin(), vec.begin() + shift, vec.end());
for(const auto& it: vec)
std::cout << it << " ";
return 0;
}
Here's a snippet :
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define MaxWords 10
int main()
{
stringstream ss;
ss.str("hi my name is aviv and");
string str[MaxWords];
int i;
for (i =0; std::getline(ss, str[i],' ');i++ )
{
cout << str[i] << " ";
}
int n;
cout << "\nEnter pos to split : ";
cin >> n;
for (int j = n; j <= i; j++)
{
cout << str[j] << " ";
}
for (int j = 0; j < n; j++)
{
cout << str[j] << " ";
}
cout << endl;
return 0;
}
Output:
I am trying to work out how I would be able to implement this autokey cipher and think that I have most of it worked out. The cipher is supposed to use a subkey style system using the characters positions in the alphabet.
Currently I am stuck on how to handle a few symbols " ;:,." when they are input as part of the encryption or decryption string and and not sure how to approach it as I am new to the language. Any guidance or direction would be wonderful. Posed the code and an example of how the cipher should work below.
Cipher Description:
#include <iostream>
#include <string>
#include <assert.h>
using namespace std;
//Declares
char autokeyE(int, int);
char autokeyD(char);
char numToLetter(int);
int letterToNum(char);
int main()
{
//Declares
string inputText, finalText;
int firstAlpha = 0;
int key = 0;
int option = 0;
//First Values
do
{
cout << "What operation would you like to do? Press '1' for Encrypt and '2' for Decrypt." << endl ;
cin >> option;
if (option == 1)
{
cout << "Please input your plain text to encrypt." << endl ;
cin >> inputText;
cout << "Please input your key to encrypt with." << endl;
cin >> key;
string finalText = "";
firstAlpha = letterToNum(inputText[0]);
finalText = numToLetter((firstAlpha + key) %26);
//inputText[0] = finalText[0];
for (int x = 1; x < inputText.length(); x++)
{
finalText += autokeyE(letterToNum(inputText[x-1]), letterToNum(inputText[x]));
}
cout << finalText << endl;
}
if (option == 2)
{
cout << "Please input your encrypted text to decrypt." << endl ;
cin >> inputText;
string finalText = "";
firstAlpha = letterToNum(inputText[0]);
finalText = numToLetter((firstAlpha + key) %26);
for (int x = 1; x < inputText.length(); x++)
{
//cout << inputText[x]; Testing output
finalText += autokeyD(inputText[x]);
}
cout << finalText << endl;
}
}
while (!inputText.length() == 0);
}
char autokeyE(int c, int n)
{
cout << "Keystream: " << n << " | Current Subkey: " << c << endl;
int result = 0;
//c = toupper(c);
result = ((c + n) +26 )%26;
cout << "C as a numtoletter: " << numToLetter(result) << " Result: " << result << endl;
return numToLetter(result);
return c;
}
char autokeyD(char c)
{
//Decrypting Shift -1
if (isalpha(c))
{
c = toupper(c);
c = (((c - 65) - 1) % 26) + 65;
}
return c;
}
char numToLetter(int n)
{
assert(n >= 1 && n <= 32);
return "ABCDEFGHIJKLMNOPQRSTUVWXYZ ;:,."[n];
}
int letterToNum(char n)
{
if (isalpha(n))
{
n = toupper(n);
return(int) n - 65;
}
else
{
cout << "REUTRNING A NON ALPHA CHARACTER AS: " << n << endl;
return(int) n -30;
}
}
I don't understand your question, but I reckon the answer would be to do a back slash before each character that does not work, like so: "\;\:\,\." ( some of these may work, so only do it on the ones that don't)
You can handle symbols using isPunct in C++ such as:
if (isPunct(inputText[x]) {
//do whatever it is you need to do
}
This question already has answers here:
Convert a String In C++ To Upper Case
(31 answers)
Closed 7 years ago.
I am writing a program that can count the number of times a word is found in a external file. The words that are to be searched for are also in an external file but I am able to retrieve those just fine. I realised that it will only update the value of count if the word exactly matches. So for example if I was searching for the word "School" and the word "school" was in the textfile I don't think the value of count would be changed. I also think that count wouldn't be changed if the word to be search for was "SCHOOL" and the word in the textfile was "school". So how do I edit my if statements so that for example the word "school" would match "SCHOOL" AND "School"?
This is my main function:
#include <iostream>
#include "ReadWords.h"
#include "Writer.h"
#include <cctype>
#include <string>
using namespace std;
int main() {
int x = 9;
int count = 0;
int count0;
int count1;
int count2;
int count3;
int count4;
int count5;
int count6;
int count7;
int count8;
int count9;
int scount;
const int size = 10;
string word_search[size];
string word;
cout << "Please enter a filename: " << flush;
char filename[30];
cin >> filename;
ReadWords reader(filename);
while (reader.isNextWord()){
count = count + 1;
reader.getNextWord();
}
cout << "There are: " << count << " words in the play" << endl;
cout << "Please enter the name of the file with the search words: " << flush;
char filename1[30];
cin >> filename1;
ReadWords reader1(filename1);
scount = 0;
while (reader1.isNextWord()) {
word_search[scount] = reader1.getNextWord();
++scount;
}
cout << "" << endl;
while (reader.isNextWord()) {
This is where I attempted to convert the input to upper case to see if the word matches the uppercase version of itself but this didn't work. Here I also need to check if the word matches itself if the first letter is capital?
if (reader.getNextWord() == word_search[0] || toupper(reader.getNextWord()) == word_search[0]) {
count0 = count0 + 1;
}
if (reader.getNextWord() == word_search[1]) {
count1 = count1 + 1;
}
if (reader.getNextWord() == word_search[2]) {
count2 = count2 + 1;
}
if (reader.getNextWord() == word_search[3]) {
count3 = count3 + 1;
}
if (reader.getNextWord() == word_search[4]) {
count4 = count4 + 1;
}
if (reader.getNextWord() == word_search[5]) {
count5 = count5 + 1;
}
if (reader.getNextWord() == word_search[6]) {
count6 = count6 + 1;
}
if (reader.getNextWord() == word_search[7]) {
count7 = count7 + 1;
}
if (reader.getNextWord() == word_search[8]) {
count8 = count8 + 1;
}
if (reader.getNextWord() == word_search[9]) {
count9 = count9 + 1;
}
}
cout << "Please enter the name of the file to write to: " << flush;
char filename2[30];
cin >> filename2;
Writer reader2(filename2);
cout << "File has been written too.." << endl;
reader2.writeInt(count);
reader2.writeString("Hello my name is Joshua Ogunnote");
return 0;
}
This is a separate file where some of my functions are declared:
#include "ReadWords.h"
#include <cstring>
#include <iostream>
using namespace std;
void ReadWords::close(){
wordfile.close();
}
ReadWords::ReadWords(const char *filename) {
wordfile.open(filename);
if (!wordfile) {
cout << "could not open " << filename << endl;
exit(1);
}
}
string ReadWords::getNextWord() {
string n;
if(isNextWord()){
wordfile >> n;
int len = n.length();
for(int i = 0; i < len ; i++) {
if (ispunct(n[i]))
{
n.erase(i--, 1);
len = n.length();
}
}
cout << n << endl;
return n;
}
}
bool ReadWords::isNextWord() {
if (wordfile.eof()) {
return false;
}
return true;
}
If you're just using English, a simple tolower() transform will do.
std::string tolower( std::string s )
{
for (char& c : s) c = std::tolower( c );
return s;
}
Now you can compare them:
if (tolower( "Hello" ) == tolower( "HELLO" ))
If you are working with Unicode, you should perform a conversion called case folding on the text, and compare the resulting string data.