简体   繁体   中英

Confusion converting decimal to hexadecimal in C++

#include <string>
#include <iostream>

using namespace std;

const string hexConversion = "0123456789ABCDEF";

int main() {
    int dec, remainder, quotient; 
    string hexNum = "";

    //input sequence
    cout << "Enter a decimal number: "; 
    cin >> dec; 
    quotient = dec; 

//conversion
    do {
        remainder = quotient % 16; 
        quotient /= 16; 
        hexNum.insert(0, hexConversion[remainder]); 
    } while (quotient != 0); 

    cout << "Your number in hex is " << hexNum << "."; 

}

I do not have a ton of experience coding, and would appreciate some insight as to what I'm doing wrong with this program! Here is the error being conveyed: invalid conversion from 'char' to 'const char*' [-fpermissive]

You are trying to use one of overloads of std::string::insert but none of them accept int and char:

One of the matching your needs is accepting position, count and symbol, so call hexNum.insert(0, 1, hexConverstion[remainder]);

If you were thinking of using the following function:

iterator insert( iterator pos, CharT ch );

you need to use:

hexNum.insert(hexNum.begin(), hexConverstion[remainder]); 

That error is coming because there is no such overloaded version of string::insert which takes int and char as arguments.

You can use this overloaded version:

 string& insert (size_t pos, size_t n, char c);                                 

where n = 1 in your case, as you want to add a character once only.

, or

iterator insert (iterator p, char c);

where p = hexNum.begin()

Checkout http://www.cplusplus.com/reference/string/string/insert/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM