Question
Hi I am writing a c++ program for converting binary numbers. My code is below for a function, but when I call the function I
Hi I am writing a c++ program for converting binary numbers. My code is below for a function, but when I call the function I get a weird error. "Debug assertion failed!" "Expression: string subscript out of range." I assume this is due to the length of a string not matching up but I am unsure of where the issue is. Any help is greatly appreciated.
string decimal_to_binary(int n) { string bin_num; // final binary string to be returned string bin_rev; int r; // to store the remainder int i = 0; //loop variable for string s
while (n > 0) {
r = n % 2;
if (r == 1) { bin_rev[i] = '1'; } else { bin_rev[i] = '0'; } n = n / 2; i++; } int l = i - 1; //i gives the length of the binary string int j = l; int k = 0; while (k <= l) {// loop to reverse string s to get the actual binary string cout << "bin[" << k << "] = " << bin_rev[k]; bin_num[j] = bin_rev[k]; //copies last character of s[i] to first character of bin_number k++; j--; }
return bin_num; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started