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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!