C++ outputs strange characters instead of numbers (Windows) - c++

I need to program a lotto generator for my education that will randomly roll numbers and check for duplicate entries and replace them otherwise. When I start the program there are no error messages and the program runs but I only see strange characters instead of numbers. A picture of the problem
What is wrong with my code?
#include <iostream>
#include <array>
#include <time.h>
std::array<unsigned char, 6> lottoZahlen = {0, 0, 0, 0, 0, 0};
void arrayFuellen();
unsigned char checkDuplikate(unsigned char);
void arraySortieren();
int main()
{
arrayFuellen();
arraySortieren();
std::cout << "\n---- Ihre Glueckszahlen lauten: ----" << std::endl;
for (unsigned char lottoGlueck : lottoZahlen)
{
std::cout << lottoGlueck << std::endl;
}
std::cout << "---- Glueckszahlen Ende ----" << std::endl;
}
void arrayFuellen()
{
srand(time(NULL));
unsigned char wuerfelZahl = 0;
unsigned char wuerfelZahlChecked = 0;
for (unsigned char i = 0; i < sizeof(lottoZahlen); i++)
{
wuerfelZahl = rand() % 45 + 1;
wuerfelZahlChecked = checkDuplikate(wuerfelZahl);
lottoZahlen[i] = wuerfelZahlChecked;
}
}
unsigned char checkDuplikate(unsigned char checkZahl)
{
srand(time(NULL));
bool dublette = false;
do
{
dublette = false;
for (unsigned char j = 0; j < sizeof(lottoZahlen); j++)
{
if (checkZahl == lottoZahlen[j])
{
checkZahl = rand() % 45 + 1;
dublette = true;
}
}
} while (dublette);
return checkZahl;
}
void arraySortieren()
{
unsigned char merker = 0;
bool vertauscht = false;
do
{
vertauscht = false;
for (unsigned char i = 1; i < sizeof(lottoZahlen); i++)
{
if (lottoZahlen[i - 1] > lottoZahlen[i])
{
merker = lottoZahlen[i];
lottoZahlen[i] = lottoZahlen[i - 1];
lottoZahlen[i - 1] = merker;
vertauscht = true;
}
}
} while (vertauscht);
}

"char" is a type that is used to store characters, and the output stream will interpret it as such in your for-loop. So if you have value 65, it will actually be displayed as a capital A (which has ASCII value 65). To display numbers, you should use a type that the output stream recognizes as a number, such as "int".

There are several ways of doing what you want, printing char as integer/decimal value:
using casging int():
std::cout << int(lottoGlueck) << "\n";
using good old (C style) printf(), some would say do not use this, but there are advantages and disadvantages to using printf().
printf("%d\n", lottoGlueck);
As suggested, you can use std::to_string(), I personally do not recommend this for printing a single character, simply because it converts a character to a string to print out an integer.
In production code I use number 1, in debugging I use 2. There are disadvantages/advantages to using both, but you can read this to better understand those.
When it comes to pinging strings as decimal values, you have std::to_string() and also std::cout << std::dec << string << "\n".

you are printing non printable characters:
https://upload.wikimedia.org/wikipedia/commons/d/dd/ASCII-Table.svg
the ones between [] are not printable characters.
if you write: int i = 5 and then std::cout << i
it will print the corresponding character, with value 5. But the value 5 is not the character '5', so if you expect it to be a printable number, you need to convert it:
std::cout << std::to_string(i)
(not sure if this was your intention though :) )

In addition to the answers to your question, you can check whether your value is printable or not by using isprint().
std::cout << isprint(lottoGlueck) << std::endl;
This will print 0 (false) if your value is non-printable.

Related

Is there an alternate way to conditionally increment array values without using if statements? C++

If have an array,
int amounts[26] = { 0, 0, 0, ...};
and I want each digit of the array to represent the amount of a different string, such that amounts[0] = amount; of 'a''s that are found within a given string, is there anyway to increment each value without using if statements?
Psuedocode example:
int amounts[26] = { 0, 0, 0, ...};
string word = "blahblah";
loop here to check and increment amounts[0] based on amount of 'a's in string
repeat loop for each letter in word.`
At the end of the loop, based on the string word, amounts should be as follows:
amounts[0] = 2 ('a')
amounts[1] = 2 ('b')
amounts[2] = 0 ('c')
// etc
Given your example, assuming the entire string is lowercase and valid characters, there's a fairly simply solution (that is to say, you handle the validation)
for (int i = 0; i < word.size(); i++) {
amounts[word[i]-'a']++; // you can also do a pre-increment if you want
}
What you want:
const char char_offset = 'a';
const int num_chars = 26;
std::vector<int> amounts(num_chars, 0);
std::string word = "blahblah";
for (auto c : word) {
int i = c - char_offset;
// this if statement is only for range checking.
// you can remove it if you are sure about the data range.
if (i >= 0 && i < num_chars) {
++amounts[i];
}
}
for (int i = 0; i < (int)amounts.size(); ++i) {
std::cout << (char)(char_offset + i) << ": " << amounts[i] << std::endl;
}
Output
a: 2
b: 2
c: 0
d: 0
e: 0
f: 0
g: 0
h: 2
i: 0
j: 0
k: 0
l: 2
m: 0
n: 0
...
Use std::unordered_map< std::string, int >. Note that std::unordered_map< char, int > would be more efficient if only a single character is required. std::string allows counting complex strings (e.g. map["substring"]++ )
Maps can be accessed using bracket notation ( e.g. map[index] ), and thus can effectively remove the need for if statements.
#include <string>
#include <unordered_map>
#include <iostream>
int main()
{
std::unordered_map< std::string, int > map = { {"a",0} };
map["a"] += 1;
std::cout << map["a"];
}
A general and portable solution would be
const std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; alphabet[i]; ++i)
amounts[i] = std::count(word.begin(), word.end(), alphabet[i]);
If you can assume the set of lowercase letters is a contiguous range, this can be simplified to
for (char c = 'a'; c <= 'z'; ++c)
amounts[c - 'a'] = std::count(word.begin(), word.end(), c);
No (overt) if in the above. Of course, there is nothing preventing std::count() being implemented using one.
The following has quite some chances of being one of the fastest in matters of counting:
std::array<unsigned int, (1U << CHAR_BIT)> counts({ });
for(auto c : word)
counts[c]++;
Getting individual values is quite efficient:
std::cout << "a: " << counts['a'] << std::endl
Iterating over the letters - well, will require a little trick:
for(char const* c = "abcdefghijklmnopqrstuvwxyz"; *c; ++c)
// case-insensitive:
std::cout << *c << ": " << counts[*c] + counts[toupper(*c)] << std::endl;
Sure, you are wasting a bit of memory - which might cost you the performance gained again: If the array does not fit into the cache any more...

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).

How to list all strings of length 12 in C++?

I'm a novice programmer studying my own. I tried to make a program that lists all strings of length 12 such as its characters are from a-z. However, there seems to be a bug I could find. It outputs for example The word is ). Could anyone tell me what I'm doing wrong, and is there some easier way to do the program?
#include <iostream>
#include <string>
int main(int argc, char *argv[])
{
using namespace std;
string l ("qwertyuiopasdfghjklzxcvbnm");
string test ("");
for(int i1 = 0;i1 < 26;++i1)
for(int i2 = 0;i2 < 26;++i2)
for(int i3 = 0;i3 < 26;++i3)
for(int i4 = 0;i4 < 26;++i4)
for(int i5 = 0;i5 < 26;++i5)
for(int i6 = 0;i6 < 26;++i6)
for(int i7 = 0;i7 < 26;++i7)
for(int i8 = 0;i8 < 26;++i8)
for(int i9 = 0;i9 < 26;++i9)
for(int i10 = 0;i10 < 26;++i10)
for(int i11 = 0;i11 < 26;++i11)
for(int i12 = 0;i12 < 26;++i12) {
test = l[i1]+l[i2]+l[i3]+l[i4]+l[i5]+l[i6]+l[i7]+l[i8]+l[i9]+l[i10]+l[i11]+l[i12];
cout << "The word is " << test << "." << endl;
test = "";
}
return 0;
}
l[i1]+l[i2] won't do what you expect. You're adding two expressions of type char so you'll get a result of type int.
An easy fix is:
test = std::string() + l[i1]+l[i2]+l[i3]+l[i4]+l[i5]+l[i6]+l[i7]+l[i8]+l[i9]+l[i10]+l[i11]+l[i12];
As I mentioned in my comment, when you see a permutations problem like this you should think of how to write a recursive algorithm.
In this case, ask yourself what each step (level) looks like. Well, you're given the string up to that point, you need to iterate through the letters, and you need to call the next level down each time so it can continue the process.
Working that out into code, "given the string up to this point" means your recursive function is passed in the prefix string, and a number indicating where it is in the chain:
void print_all_strings(const std::string& prefix, unsigned remain) {
Iterating through the letters is something you've already got (use a for loop), but the way you're doing it is not great. Instead of typing all the characters into a string and iterating through those characters, you're better off realizing that you can iterate through characters in a for loop like you can iterate through numbers, since characters are numbers in C++ (and C). In other words, 'a' + 1 == 'b' and so forth. So your loop becomes:
for(char c = 'a'; c <= 'z'; c++)
Finally, you need to handle the next level down. That means using the prefix and remain parameters to figure out what to do next. Well, there's one thing we know: if there are 0 letters left, then don't add a letter, but instead print the string and return!
if(remain == 0) {
cout << "The word is " << prefix << "." << endl;
return;
}
In other cases, we need to add a letter. That's where std::string + char => std::string comes in. (Note that char + char => char!)
print_all_strings(prefix + c, remain - 1);
Putting it all together:
void print_all_strings(const std::string& prefix, unsigned remain) {
if(remain == 0) {
cout << "The word is " << prefix << "." << endl;
return;
}
for(char c = 'a'; c <= 'z'; c++)
print_all_strings(prefix + c, remain - 1);
}
int main(int argc, char *argv[])
{
print_all_strings("", 12);
return 0;
}
But then, as CiaPan explained, your computer will die before this program finishes.

How would I cycle through all of the various possibilities in this situation?

I saw a programming assignment that I decided to try, and it's basically where the user inputs something like "123456789=120", and the program has to insert a '+' or '-' at different positions to make the statement true. For example, in this case, it could do 123+4-5+6-7+8-9 = 120. There are only 3^8 possible combinations, so I think it would be okay to brute force it, but I don't know exactly in what order I could go in/how to actually implement that. More specifically, I don't know what order I would go in in inserting the '+' and '-'. Here is what I have:
#include <iostream>
#include <cmath>
using namespace std;
int string_to_integer(string);
int main()
{
string input, result_string;
int result, possibilities;
getline(cin, input);
//remove spaces
for(int i = 0; i < input.size(); i++)
{
if(input[i] == ' ')
{
input.erase(i, 1);
}
}
result_string = input.substr(input.find('=') + 1, input.length() - input.find('='));
result = string_to_integer(result_string);
input.erase(input.find('='), input.length() - input.find('='));
possibilities = pow(3, input.length() - 1);
cout << possibilities;
}
int string_to_integer(string substring)
{
int total = 0;
int power = 1;
for(int i = substring.length() - 1; i >= 0; i--)
{
total += (power * (substring[i] - 48));
power *= 10;
}
return total;
}
The basic idea: generate all the possible variations of +, - operators (including the case where the operator is missing), then parse the string and obtain the sum.
The approach: combinatorially, it is easy to show that we can do this by associating the operators (or the absence thereof) with the base-3 digits. So we can just iterate over every 8-digit ternary number, but instead of printing 0, 1 and 2, we will append a "+", a "-" or nothing before the next digit in the string.
Note that we do not actually need a string for this; one could use digits and operators etc. directly as well, computing the result on the fly. I only took the string-based approach because it's simple to explain, trivial to implement, and additionally, it gives us some visual feedback, which helps understanding the solution.
Now that we have constructed our string, we can just parse it; the simplest solution is to use the C standard library function strtol() for this purpose, which will take signs into account and it will return a signed integer. Because of this, we can just sum all the signed integers in a simple loop and we are done.
Code:
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
int main()
{
const char *ops = " +-";
// 3 ^ 8 = 6561
for (int i = 0; i < 6561; i++) {
// first, generate the line
int k = i;
std::string line = "1";
for (int j = 0; j < 8; j++) {
if (k % 3)
line += ops[k % 3];
k /= 3;
line += (char)('2' + j);
}
// now parse it
int result = 0;
const char *s = line.c_str();
char *p;
while (*s) {
int num = strtol(s, &p, 10);
result += num;
s = p;
}
// output
std::cout << line << " = " << result << (result == 120 ? " MATCH" : "") << std::endl;
}
return 0;
}
Result:
h2co3-macbook:~ h2co3$ ./quirk | grep MATCH
12-3-45+67+89 = 120 MATCH
1+2-34-5+67+89 = 120 MATCH
12-3+4+5+6+7+89 = 120 MATCH
1-23+4+56-7+89 = 120 MATCH
1+2+34-5+6-7+89 = 120 MATCH
123+4+5-6-7-8+9 = 120 MATCH
1+2-3+45+6+78-9 = 120 MATCH
12-3+45+67+8-9 = 120 MATCH
123+4-5+6-7+8-9 = 120 MATCH
123-4+5+6+7-8-9 = 120 MATCH
h2co3-macbook:~ h2co3$
The following bool advance(string& s) function will give you all combinations of '+', '-' and ' ' strings of arbitrary length except one and return false if no more are available.
char advance(char c)
{
switch (c)
{
case ' ': return '+';
case '+': return '-';
default: case '-': return ' ';
}
}
bool advance(string& s)
{
for (int i = 0; i < s.size(); ++i)
if ((s[i] = advance(s[i])) != ' ')
return true;
return false;
}
You have to first feed it with a string containing only spaces having desired length and then repeat 'advancing' it. Usage:
string s = " ";
while (advance(s))
cout << '"' << s << '"' << endl;
The above code will print
"+ "
"- "
" + "
"++ "
"-+ "
" - "
.
.
.
" ---"
"+---"
"----"
Note that the 'first' combination with just 4 spaces is not printed.
You can interleave those combinations with your lhs, skipping spaces, to produce expressions.
Another very similar approach, in plain C OK, in C++ if you really want it that way ;) and a bit more configurable
The same base 3 number trick is used to enumerate the combinations of void, + and - operators.
The string is handled as a list of positive or negative values that are added together.
The other contribution is very compact and elegant, but uses some C tricks to shorten the code.
This one is hopefully a bit more detailled, albeit not as beautiful.
#include <iostream>
#include <string>
using namespace std;
#include <string.h>
#include <math.h>
void solver (const char * str, int result)
{
int op_max = pow(3, strlen(str)); // number of operator permutations
// loop through all possible operator combinations
for (int o = 0 ; o != op_max ; o++)
{
int res = 0; // computed operation result
int sign = 1; // sign of the current value
int val = str[0]-'0'; // read 1st digit
string litteral; // litteral display of the current operation
// parse remaining digits
int op;
for (unsigned i=1, op=o ; i != strlen (str) ; i++, op/=3)
{
// get current digit
int c = str[i]-'0';
// get current operator
int oper = op % 3;
// apply operator
if (oper == 0) val = 10*val + c;
else
{
// add previous value
litteral += sign*val;
res += sign*val;
// store next sign
sign = oper == 1 ? 1 : -1;
// start a new value
val = c;
}
}
// add last value
litteral += sign*val;
res += sign*val;
// check result
if (res == result)
{
cout << litteral << " = " << result << endl;
}
}
}
int main(void)
{
solver ("123456789", 120);
}
Note: I used std::strings out of laziness, though they are notoriously slow.

Octal conversion using loops in C++

I am currently working on a basic program which converts a binary number to an octal. Its task is to print a table with all the numbers between 0-256, with their binary, octal and hexadecimal equivalent. The task requires me only to use my own code (i.e. using loops etc and not in-built functions). The code I have made (it is quite messy at the moment) is as following (this is only a snippit):
int counter = ceil(log10(fabs(binaryValue)+1));
int iter;
if (counter%3 == 0)
{
iter = counter/3;
}
else if (counter%3 != 0)
{
iter = ceil((counter/3));
}
c = binaryValue;
for (int h = 0; h < iter; h++)
{
tempOctal = c%1000;
c /= 1000;
int count = ceil(log10(fabs(tempOctal)+1));
for (int counter = 0; counter < count; counter++)
{
if (tempOctal%10 != 0)
{
e = pow(2.0, counter);
tempDecimal += e;
}
tempOctal /= 10;
}
octalValue += (tempDecimal * pow(10.0, h));
}
The output is completely wrong. When for example the binary code is 1111 (decimal value 15), it outputs 7. I can understand why this happens (the last three digits in the binary number, 111, is 7 in decimal format), but can't be able to identify the problem in the code. Any ideas?
Edit: After some debugging and testing I figured the answer.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
while (true)
{
int binaryValue, c, tempOctal, tempDecimal, octalValue = 0, e;
cout << "Enter a binary number to convert to octal: ";
cin >> binaryValue;
int counter = ceil(log10(binaryValue+1));
cout << "Counter " << counter << endl;
int iter;
if (counter%3 == 0)
{
iter = counter/3;
}
else if (counter%3 != 0)
{
iter = (counter/3)+1;
}
cout << "Iterations " << iter << endl;
c = binaryValue;
cout << "C " << c << endl;
for (int h = 0; h < iter; h++)
{
tempOctal = c%1000;
cout << "3 digit binary part " << tempOctal << endl;
int count = ceil(log10(tempOctal+1));
cout << "Digits " << count << endl;
tempDecimal = 0;
for (int counterr = 0; counterr < count; counterr++)
{
if (tempOctal%10 != 0)
{
e = pow(2.0, counterr);
tempDecimal += e;
cout << "Temp Decimal value 0-7 " << tempDecimal << endl;
}
tempOctal /= 10;
}
octalValue += (tempDecimal * pow(10.0, h));
cout << "Octal Value " << octalValue << endl;
c /= 1000;
}
cout << "Final Octal Value: " << octalValue << endl;
}
system("pause");
return 0;
}
This looks overly complex. There's no need to involve floating-point math, and it can very probably introduce problems.
Of course, the obvious solution is to use a pre-existing function to do this (like { char buf[32]; snprintf(buf, sizeof buf, "%o", binaryValue); } and be done, but if you really want to do it "by hand", you should look into using bit-operations:
Use binaryValue & 3 to mask out the three lowest bits. These will be your next octal digit (three bits is 0..7, which is one octal digit).
use binaryValue >>= 3 to shift the number to get three new bits into the lowest position
Reverse the number afterwards, or (if possible) start from the end of the string buffer and emit digits backwards
It don't understand your code; it seems far too complicated. But one
thing is sure, if you are converting an internal representation into
octal, you're going to have to divide by 8 somewhere, and do a % 8
somewhere. And I don't see them. On the other hand, I see a both
operations with both 10 and 1000, neither of which should be present.
For starters, you might want to write a simple function which converts
a value (preferably an unsigned of some type—get unsigned
right before worrying about the sign) to a string using any base, e.g.:
//! \pre
//! base >= 2 && base < 36
//!
//! Digits are 0-9, then A-Z.
std::string convert(unsigned value, unsigned base);
This shouldn't take more than about 5 or 6 lines of code. But attention,
the normal algorithm generates the digits in reverse order: if you're
using std::string, the simplest solution is to push_back each digit,
then call std::reverse at the end, before returning it. Otherwise: a
C style char[] works well, provided that you make it large enough.
(sizeof(unsigned) * CHAR_BITS + 2 is more than enough, even for
signed, and even with a '\0' at the end, which you won't need if you
return a string.) Just initialize the pointer to buffer +
sizeof(buffer), and pre-decrement each time you insert a digit. To
construct the string you return:
std::string( pointer, buffer + sizeof(buffer) ) should do the trick.
As for the loop, the end condition could simply be value == 0.
(You'll be dividing value by base each time through, so you're
guaranteed to reach this condition.) If you use a do ... while,
rather than just a while, you're also guaranteed at least one digit in
the output.
(It would have been a lot easier for me to just post the code, but since
this is obviously homework, I think it better to just give indications
concerning what needs to be done.)
Edit: I've added my implementation, and some comments on your new
code:
First for the comments: there's a very misleading prompt: "Enter a
binary number" sounds like the user should enter binary; if you're
reading into an int, the value input should be decimal. And there are
still the % 1000 and / 1000 and % 10 and / 10 that I don't
understand. Whatever you're doing, it can't be right if there's no %
8 and / 8. Try it: input "128", for example, and see what you get.
If you're trying to input binary, then you really have to input a
string, and parse it yourself.
My code for the conversion itself would be:
//! \pre
//! base >= 2 && base <= 36
//!
//! Digits are 0-9, then A-Z.
std::string toString( unsigned value, unsigned base )
{
assert( base >= 2 && base <= 36 );
static char const digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char buffer[sizeof(unsigned) * CHAR_BIT];
char* dst = buffer + sizeof(buffer);
do
{
*--dst = digits[value % base];
value /= base;
} while (value != 0);
return std::string(dst, buffer + sizeof(buffer));
}
If you want to parse input (e.g. for binary), then something like the
following should do the trick:
unsigned fromString( std::string const& value, unsigned base )
{
assert( base >= 2 && base <= 36 );
static char const digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
unsigned results = 0;
for (std::string::const_iterator iter = value.begin();
iter != value.end();
++ iter)
{
unsigned digit = std::find
( digits, digits + sizeof(digits) - 1,
toupper(static_cast<unsigned char>( *iter ) ) ) - digits;
if ( digit >= base )
throw std::runtime_error( "Illegal character" );
if ( results >= UINT_MAX / base
&& (results > UINT_MAX / base || digit > UINT_MAX % base) )
throw std::runtime_error( "Overflow" );
results = base * results + digit;
}
return results;
}
It's more complicated than toString because it has to handle all sorts
of possible error conditions. It's also still probably simpler than you
need; you probably want to trim blanks, etc., as well (or even ignore
them: entering 01000000 is more error prone than 0100 0000).
(Also, the end iterator for find has a - 1 because of the trailing
'\0' the compiler inserts into digits.)
Actually I don't understand why do you need so complex code to accomplish what you need.
First of all there is no such a thing as conversion from binary to octal (same is true for converting to/from decimal and etc.). The machine always works in binary, there's nothing you can (or should) do about this.
This is actually a question of formatting. That is, how do you print a number as octal, and how do you parse the textual representation of the octal number.
Edit:
You may use the following code for printing a number in any base:
const int PRINT_NUM_TXT_MAX = 33; // worst-case for binary
void PrintNumberInBase(unsigned int val, int base, PSTR szBuf)
{
// calculate the number of digits
int digits = 0;
for (unsigned int x = val; x; digits++)
x /= base;
if (digits < 1)
digits = 1; // will emit zero
// Print the value from right to left
szBuf[digits] = 0; // zero-term
while (digits--)
{
int dig = val % base;
val /= base;
char ch = (dig <= 9) ?
('0' + dig) :
('a' + dig - 0xa);
szBuf[digits] = ch;
}
}
Example:
char sz[PRINT_NUM_TXT_MAX];
PrintNumberInBase(19, 8, sz);
The code the OP is asking to produce is what your scientific calculator would do when you want a number in a different base.
I think your algorithm is wrong. Just looking over it, I see a function that is squared towards the end. why? There is a simple mathematical way to do what you are talking about. Once you get the math part, then you can convert it to code.
If you had pencil and paper, and no calculator (similar to not using pre built functions), the method is to take the base you are in, change it to base 10, then change to the base you require. In your case that would be base 8, to base 10, to base 2.
This should get you started. All you really need are if/else statements with modulus to get the remainders.
http://www.purplemath.com/modules/numbbase3.htm
Then you have to figure out how to get your desired output. Maybe store the remainders in an array or output to a txt file.
(For problems like this is the reason why I want to double major with applied math)
Since you want conversion from decimal 0-256, it would be easiest to make functions, say call them int binary(), char hex(), and int octal(). Do the binary and octal first as that would be the easiest since they can represented by only integers.
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>
using namespace std;
char* toBinary(char* doubleDigit)
{
int digit = atoi(doubleDigit);
char* binary = new char();
int x = 0 ;
binary[x]='(';
//int tempDigit = digit;
int k=1;
for(int i = 9 ; digit != 0; i--)
{
k=1;//cout << digit << endl;
//cout << "i"<< i<<endl;
if(digit-k *pow(8,i)>=0)
{
k =1;
cout << "i" << i << endl;
cout << k*pow(8,i)<< endl;
while((k*pow(8,i)<=digit))
{
//cout << k <<endl;
k++;
}
k= k-1;
digit = digit -k*pow(8,i);
binary[x+1]= k+'0';
binary[x+2]= '*';
binary[x+3]= '8';
binary[x+4]='^';
binary[x+5]=i+'0';
binary[x+6]='+';
x+=6;
}
}
binary[x]=')';
return binary;
}
int main()
{
char value[6]={'4','0','9','8','7','9'};
cout<< toBinary(value);
return 0 ;
}