Using C++. My code asks the user for a string input, prints that string back to them in binary, prompts them to enter some binary, and then converts that binary back to a string. When testing the code I enter a string like "bed" and reenter the binary in returns me. When it converts the binary back I will end up with "bbb" so its returning the first 8 bits * the segments of 8.
Any suggestions on fixing this? It seems like my a variable is starting back to 0. I've tried for( int a = z;.....) and this just prints the first 8 bits only( "bed" -> binary -> "b")
My code is:
#include <iostream>
#include <string>
#include <cmath>
#include <bitset>
using namespace std;
int main()
{
string stuff;
cout << "type some stuff :" << endl;
getline(cin, stuff);
int convert = 0,
toconvert = 0;
for(int i = 0; i < stuff.length(); i++)
{
cout << bitset<8>(stuff.at(i));
}
string retype;
cout << "type in some sweet binary:" << endl;
getline(cin, retype);
char mycharacter;
for(int z = 0; z < retype.length(); z += 8 )
{
for(int a = 0; a < retype.length(); a++)
{
if (retype.at(a) == '1' )
{
convert = (int)pow( 2,( 7- a));
toconvert = toconvert + convert;
}
else if (retype.at(a) == '0')
{
toconvert = toconvert + 0;
}
else
{
cout << "you did not type binary, try again" << endl;
}
}
mycharacter = char(toconvert);
cout << mycharacter;
toconvert = 0;
}
cout << " " << endl;
return 0;
}
Related
I have something which outputs all the factors for an integer using a fixed loop.
in this case, int_end_int_ = 4
and middle_x_coefficient = 4
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0) // This gets the factors
{
//here
}
}
i have that inside the if loop that if i * 2 == 4, print a string. So i thought that when i = 2, it will output the string.
//inside if loop
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i; //ignore
cout << "prerooted";
preroot2 = i; //ignore
}
It does not output "prerooted", and i have no clue why.
Full Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Quadratic Equation Solver ( to roots )" << endl;
cout << "Enter quadratic equation, e.x (x^2 + 4x + 4) must be in this form" << endl;
string equation;
cout << ">> ";
getline(cin, equation);
if (equation.length() < 12)
{
cout << "Please enter valid string." << endl;
while (equation.length() < 12)
{
cout << ">> ";
getline(cin, equation);
}
}
char middle_x_coefficient = equation[6]; // getting x^2 + 4(this<-)x + 4
char end_int_ = equation[11]; // getting x^2 + 4x + 4 <-- this
int preroot1 = 0;
int preroot2 = 0;
int int_end_int_ = static_cast<int>(end_int_); //convert char to int using static cast for like no reason
//nvm <- https://stackoverflow.com/questions/103512/why-use-static-castintx-instead-of-intx this says it is better bc compiler bad or smthn
int_end_int_ -= 48; //This converts the ascii value (52 for 4) to 4 (-48)
int pasti = 0;
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0)
{
cout << i << "this<- i" << endl;
cout << middle_x_coefficient << "this<- x" << endl;
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i;
cout << "prerooted";
preroot2 = i;
}
else if (i + pasti == middle_x_coefficient) {
preroot1 = i;
preroot2 = pasti;
}
pasti = i;
}
}
cout << preroot1 << " " << preroot2 << endl;
return 0;
}
You converted the character end_int_ to the integer int_end_int_, but you didn't convert the character middle_x_coefficient to an integer. Convert and use converted integer just as you did for end_int_.
Instead of using magic number 48, using character literal '0' is better.
I'm having difficulty printing a reversed number. The algorithm is working as expected for the reversal of the user's input but cannot display correctly:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int rem, OriValue, InValue2 = 0, InValue = 0;//rem = remainder,InValue = User input
bool neg = false; // Boolean Variable to remember input value
//Request customer to enter a int value
cout << "Enter any decimal integer value >= 0:";
cin >> InValue;
OriValue = InValue;
if(InValue < 0)
{
neg = true;
InValue = -InValue;
cout << "Input value is negative :" << InValue <<"\n";
}
else if (InValue > 0 )
cout << "Input value is positive:"<< InValue <<"\n";
do
{
rem = (InValue % 10);
cout << "Remainder value:"<< rem << "\n";
InValue = InValue / 10;
}
while (InValue != 0);
cout << OriValue << " in reverse is " << InValue << "\n";
// Here is an example of the output:
// -123 in reverse 321
return 0;
}
How can I resolve the problem?
This shoule do the work. Check the comments in the code
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int rem, OriValue, InValue2 = 0, InValue = 0;//rem = remainder,InValue = User input
int reverseVal = 0; // Add this variable to store the reverse number
bool neg = false; // Boolean Variable to remember input value
//Request customer to enter a int value
cout << "Enter any decimal integer value >= 0:";
cin >> InValue;
OriValue = InValue;
if(InValue < 0)
{
neg = true;
InValue = -InValue;
cout << "Input value is negative :" << InValue <<"\n";
}
else if (InValue > 0 )
cout << "Input value is positive:"<< InValue <<"\n";
do
{
rem = (InValue % 10);
cout << "Remainder value:"<< rem << "\n";
InValue = InValue / 10;
// Add this to store
reverseVal = reverseVal*10 + rem;
}
while (InValue != 0);
cout << OriValue << " in reverse is " << reverseVal << "\n";
// Here is an example of the output:
// -123 in reverse 321
return 0;
}
You haven't stored your reversed variable anywhere, and n == 0 is when your loop terminates. When you print n after your loop ends, it has to be 0 as you're seeing. The solution is to store your remainders as you divide down n.
Here are a couple options for achieving this.
Using stringstream:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int original_value, n;
stringstream ss;
cout << "Enter an integer >= 0:";
cin >> original_value;
n = original_value;
if (n < 0) {
n = -n;
ss << '-';
}
while (n > 0) {
ss << n % 10;
n /= 10;
}
cout << original_value << " in reverse is " << ss.str() << "\n";
return 0;
}
Using reverse:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n = -1234;
string rev = to_string(n);
reverse(rev.begin() + (rev[0] == '-' ? 1 : 0), rev.end());
cout << rev << "\n";
return 0;
}
Sample run:
Enter an integer >= 0: -1234
-1234 in reverse is -4321
If you need an integer at the end, you can always parse it from the string using atoi, istringstream or stoi.
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)
Ok I have been struggling with this code and I think I have it written out right but here is the rules from my teacher
1 = implies right Number, Right Place.
2 = implies right Number, Wrong Place.
0 = implies Wrong Number.
So the computer decides on 12345; the user guesses 11235; the computer should respond with 10221. Hint: Watch out for a double number like 11 when there is only one.
I have it where it does all of that except I can not get it to show a 0 when it is wrong can you please help me every single part is written except that part here is my code
// Programming 2
// Mastermind
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
struct fields{//the list of variables used in my program
int size = 5;;
int range = 9;
char lowest = '0';
string guess;
string answer;
int number;
int correct;
int position;
bool gameover = false;
};
void gameplay(fields & info);//declaring the function
int main()
{
fields game;
gameplay(game);//calling the function
system("pause");
return 0;
}
void gameplay(fields & info){//calling the structure into the function
srand(time(0));//to randomize number
info.answer = "";//getting the number
for (int i = 0; i < info.size; i++)
{
char ch = info.lowest + rand() % info.range;
info.answer += ch;
}
info.number = 1;
info.correct = 0;
info.position = 0;
while (!info.gameover)//using a while loop to let them go until they guess it
{
cout << "Guess #" << info.number << ": Enter 5 numbers that are '0' through '9': ";//asking them to guess
cout << info.answer;
cout << "\n";
cin >> info.guess;
if (info.guess == info.answer)//if the guess is right this will end the game
{
cout << "Right! It took you " << info.number << " move";
if (info.number != 1) cout << "s";
cout << "." << endl;
info.gameover = true;
}
int correctNumbers = 0;
for (char const &ch : info.guess) //seeing if there are numebrs in the guess that is in the answer
{
if (info.answer.find(ch) != string::npos)
{
++correctNumbers;
}
}
int const digits = 5;
int correctPositions = 0;
int correctPosition[digits];
int test = 0;
for (int i = 0; i < digits; ++i)//telling which numbers is correct and displaying the 2 or 0 for number is correct or number is wrong
{
if (info.answer[i] == info.guess[i])
{
++correctPositions;
}
if (info.answer[i] == info.guess[i]){
correctPosition[i] = 2;
cout << correctPosition[i];
}
if (correctPosition[i] != 2){
correctPosition[i] = 1;
cout << correctPosition[i];
}
if (correctPosition[i] != 2 && correctPosition[i] != 1)){
correctPosition[i] = 0;
cout << correctPosition[i];
}
}
cout << "\nYou have " << correctPositions << " numbers in the correct position " <<endl;
cout << "You have " << correctNumbers <<" correct numbers in the wrong position"<< endl;
}
cout << "GAME OVER\n\n";
}
I'm making a program that converts a string that the user enters such as "APPLE" into a binary number through the corresponding ASCII numbers that represent each character of the string "APPLE." For example A = 65 in ascii etc.. I've created a function that converts the string into a binary but it doesn't seem to be working. It displays "The equivalent binary number is: 0031F240for A" in an infinite loop and gives me "0031F240for" instead of being in the binary version of 65. I know this function works for converting a decimal number into binary because I've tried it, but I think my implementation of the bin[] array is messing things up. Any help would be appreciated.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <fstream>
using namespace std;
class RandomString
{
private:
string input;
string bin[100];
public:
RandomString() : bin(), input("")
{
}
void getData()
{
cout << "Enter the word to be encoded into a binary file.";
cin >> input;
}
void numToBin()
{
int i = 0;
int len = input.length();
int num = int(input[i]);
for(int i = 0; i < len; i++)
{
while(num != 0)
{
if (num % 2 == 0)
bin[i].insert(0, "0");
else
bin[i].insert(0, "1");
num = num / 2;
cout << "The equivalent binary number is: " << bin << "for " << input[i] << endl;
}
}
}
void display()
{
}
};
I haven't test if the result is correct but this code convert a string to binary. Probably you have to modify it to fit with ASCII codes.
void DecimalToBinary(char a,std::vector<char>& v)
{
if(a==0)
v.push_back(0);
if(a==1)
v.push_back(1);
else
{
v.push_back(a%2);
DecimalToBinary(a/2,v);
}
}
int main()
{
std::vector<char> v;
std::string line;
getline(std::cin,line);
std::istringstream input(line);
char c;
while(input >> c)
{
DecimalToBinary(c,v);
}
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(std::cout,""));
}
First Your while loop never stops because you don't change the value of i inside the while loop, so int(input[i]) has always the same value, you have to use break somewhere or i++, but I don't know if the result is correct,I think recursion is better than while in this situation, but anyway try the following:
void numToBin()
{
int i = 0;
int len = input.length();
int num = int(input[i]);
for(int i = 0; i < len; i++)
{
while(int(input[i]) != 0)
{
if (num % 2 == 0)
{
bin[i].insert(0, "0");
break;
}
else
{
bin[i].insert(0, "1");
num = num / 2;
}
cout << "The equivalent binary number is: " << bin << "for " << input[i] << endl;
}
}
}
Second, doing std::cout << bin you print a memory address, not the contents of the bin.
while(int(input[i]) != 0)
{
if (num % 2 == 0)
bin[i].insert(0, "0");
else
{
bin[i].insert(0, "1");
}
num = num / 2;// this line should be in both case.
cout << "The equivalent binary number is: " << bin << "for " << input[i] << endl;
}
I've changed num = num / 2 for both cases. Please check it.
You may want to change the 'bin' in
cout << "The equivalent binary number is: " << bin
to 'bin[i]'.
Because 'bin' is a string array, also the pointer/address to the string array, so 'cout << bin' will always output the address.