Having trouble with converting a decimal number to a binary - c++

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.

Related

Binary String to Integer Stack [duplicate]

This question already has answers here:
Convert single char to int
(3 answers)
Closed 2 years ago.
Struggling to separate a string into a stack containing 1's and 0's. Currently I am trying to iterate through the string and parse them into integers to add to a stack.
I am entering 1010, in which the result is 1010 , 010, 10, 0 instead of the desired stack being 1, 0, 1, 0
I have used atoi and stoi along with indexing and the .at method to where I still have the same issue.
#include <iostream>
#include <string>
#include <stack>
using namespace std;
bool isParsableInt(string input) {
string nums = "1234567890";
string test = input;
int attempt;
try {
if (test == "") { return false; }
if (test[0] == '-') {
test = test.substr(1, test.length() - 1);
}
for (int i = 0; i < test.length(); i++) {
if (nums.find(test[i]) == string::npos) { return false; }
attempt = atoi(&test[i]); // String to integer
}
return true;
}
catch (...) { // Catches any error thrown
return false;
}
}
stack<int> createBinaryStack() {
string input;
stack<int> result = stack<int>();
while (true){
cout << "Enter a binary number : ";
cin >> input;
if (!isParsableInt(input)) {
cout << "Invalid Input found - Must be 1's & 0's" << endl;
continue;
}
if (count(input, '0') + count(input, '1') != input.length()) {
cout << "Invalid Number found - Must be 1's & 0's" << endl;
continue;
}
for (int i = 0; i < input.length(); i++) {
cout << stoi(&input.at(i)) << "\t"; // Issue on atoi and stoi functions do not seem to work
result.push(stoi(&input.at(i)));
}
cout << endl;
return result;
}
}
int binaryStackToDecimal(stack<int> stk){
int count = stk.size();
int total = 0;
for (int i = 0; i < count; i++) {
if (stk.top() != 1 && stk.top() != 0) {
return -1;
}
total += stk.top() * pow(2, i);
stk.pop();
}
return total;
}
int main(){
stack<int> stk = createBinaryStack();
while (!stk.empty()) {
cout << stk.top();
stk.pop();
}
cout << endl;
cout << binaryStackToDecimal(stk);
}
stoi(&input.at(i))
should be
input.at(i) - '0'
or, since you are only dealing with zero and one the even simpler
input.at(i) == '1'
also works (as do many other variations).
Your mistake was taking functions that are intended to convert a sequence of digits to a number (stoi and atoi) when all you wanted to do is convert a single digit.

C++ if statement not printing desired output

Problem is with the if statment inside the while loop. It is not printing the desired output. The else if statement and the else statement seem to work fine
Any help is appreciated
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
while (sum < input) {
// This is the if statement giving me problems
if (input == 1) {
exponent += 1;
sum = 3;
}
// This else if statement seems to work fine
else if (input == 3) {
exponent += 2;
sum = 9;
}
else {
exponent++;
sum *= base;
}
}
// Print output
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
Your logic is wrong (and I have to say a bit bizarre).
If the input is 1 then while (sum < input) is not true and so you never reach your if (input == 1) statement.
REALIZED my mistake. i just moved the if and else if statement to outside the loop
#include <iostream>
using namespace std;
/*
Write a C++ program that asks the user for an integer.
The program finds and displays the first power of 3
larger than the input number using while
*/
int main() {
int input = 0;
int base = 3;
int exponent = 0;
int sum = 1;
cout << "Enter a number: ";
cin >> input;
if (input == 1) {
exponent += 1;
sum = 3;
}
else if (input == 3) {
exponent += 2;
sum = 9;
}
while (sum < input) {
exponent++;
sum *= base;
}
cout << "3 to the power of " << exponent << " is equal to " << sum;
cout << endl << "It is the first power of 3 larger than " << input;
return 0;
}
If I understood the objective right from the comments, if conditions are not required. Just replace the condition and simplify the while loop as follows:
while (sum <= input) {
exponent++;
sum *= base;
}
Write a C++ program that asks the user for an integer. The program
finds and displays the first power of 3 larger than the input number
using while
You should probably calculate the answer instead of looping.
#include <iostream>
#include <cmath>
int main() {
int input;
std::cout << "input: ";
std::cin >> input;
int x = 0;
/*
3^x == input
ln(3^x) == ln(input)
x*ln(3) == ln(input)
x == ln(input)/ln(3)
*/
// calculate x = ln(input)/ln(3), round down and add 1
if(input > 0) x = std::floor(std::log(input) / std::log(3.)) + 1.;
std::cout << "answer: 3^" << x << " == " << std::pow(3, x) << "\n";
}

Reversing a number C++

Looking for some advice here on what I'm getting wrong. Everything in my main should be fine and left unchanged. My problem is in my reverse function. It's printing the reversed number right before the cout statement of "The number is" instead down below where it should be. I spent awhile trying to fix but can't come up with a solution.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
const int NUM_VALS = 10; //the maximum number of values to use
int reverse(int num);
bool isPrime(int num);
int main()
{
int number, //Holds the random number that is manipulated and tested
loopCnt; //Controls the loop
//set the seed value for the random number generator
//Note: a value of 1 will generate the same sequence of "random" numbers every
// time the program is executed
srand(1);
//Generate 10 random numbers to be manipulated and tested
for( loopCnt = 1; loopCnt <= NUM_VALS; loopCnt++ )
{
//Get a random number
number = rand();
//Display the sum of adding up the digits in the random number, the reversed
//random number, and whether or not the number is palindromic or a prime number
cout << "The number is " << number << endl
<< "----------------------------------------" << endl
// << "Adding the digits result" << setw(16) << sumDigits( number ) << endl
<< "Reversing the digits result" << setw(13) << reverse(number) << endl
// << "Is the number a palindrome?" << setw(13) << (isPalindrome(number)? "Yes" : "No") << endl
// << "Is the number prime?" << setw(20) << (isPrime(number)? "Yes" : "No") << endl
<< endl << endl;
}
return 0;
}
int reverse(int num)
{
int quo, rem;
quo = num;
while (quo != 0)
{
rem = quo % 10;
cout << rem;
quo /= 10;
}
}
bool isPrime(int num)
{
int i;
if (num % 2 == 0)
return false;
for (i = 3; i*i <= num; i+=2)
{
if (num % i == 0)
return false;
}
return true;
}
You need to have your reverse function return the number as reversed, because the return value is used in main.
You can build the reversed number by multiplying a "reversed" value by 10, then adding in the remainder:
int reverse(int num)
{
int reversed = 0;
int quo, rem;
quo = num;
while (quo != 0)
{
rem = quo % 10;
reversed = reversed * 10 + rem;
quo /= 10;
}
return reversed;
}
You can also use this method to reverse a number by taking string input and then reverse it and convert it to int.
#include <iostream>
#include<string>
using namespace std;
int reverse_num(string a)
{
string s;
for(int i=a.length()-1;i>=0;i--)
{
s+=a[i];
}
int n;
n=stoi(s);
return n;
}
int main()
{
string a;
cin>> a;
cout<<reverse_num(a);
return 0;
}

converting binary to string, only converting first 8 bits

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;
}

Mastermind string cout issue

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";
}