удаление пространства имен std, в частности sprintf, в программе C ++ типа denary to hex - PullRequest
0 голосов
/ 11 марта 2019

Я закодировал преобразователь деньри в шестнадцатеричный код и пытаюсь найти способ удалить встроенную функцию sprinf, а также встроенную функцию стои, которую я использовал, потому что, поскольку я использую c ++, мне говорят, что я использую пространство имен std Это плохая практика, но я не могу придумать, как это сделать, не нарушив мою программу, и мы будем благодарны за любую помощь.

также я оставил свои комментарии в своем коде для будущих вопросов. Должен ли я удалить их или оставить их при публикации спасибо

#include <iostream>
#include <string>
#pragma warning(disable:4996)

using namespace std;

int DecToHex(int Value) //this is my function 
{
char *CharRes = new (char); //crestes the variable CharRes as a new char 

//sprintf is part of the standard library 
sprintf(CharRes, "%X", Value);  
//char res is the place the concerted format will go 
//value is the value i want to convert    
//%X outputs a hex number        
//snprintf covers the formatting of a string                          

int intResult = stoi(CharRes); //stoi is a function in the library 

std::cout << intResult << std::endl; //print int results to the screen

return intResult; //returns int result 
}



int main()
{
int a;

std::cout << "Please enter a number" << std::endl;

std::cin >> a; //stores the value of a 

DecToHex(a); //runs the function 

system("pause"); //pauses the system 

return 0; //closes the program 
}

1 Ответ

0 голосов
/ 11 марта 2019

Поток в C ++ уже имеет встроенную функцию для преобразования формата, такого как десятичный / шестнадцатеричный и т. Д., Поэтому вы можете просто сделать это:

int main()
{
    int a;
    std::cout << "Please enter a number" << std::endl;

    std::cin >> a; //stores the value of a   
    std::cout << std::hex; // Set the formating to hexadecimal
    std::cout << a; // Put your variable in the stream
    std::cout << std::dec;, // Return the format to decimal. If you want to keep the hexa format you don't havr to do this
    std::cout << std::endl; // Append end line and flush the stream

    /* This is strictly equivalent to : */
    std::cout << std::hex << a << std::dec << std::endl;

    system("pause"); //pauses the system 
    return 0; //closes the program 
}

Использование std :: hex в потоке выведет значение вгекс.Использование std :: dec выведет значение в десятичном формате.Использование std :: octa напечатает значение в восьмеричном формате.

Вы можете вызывать любую функцию из стандартной библиотеки, не используя using namespace std, просто добавив к ней префикс std::.Например, std::snprintf, std::stoi и т. Д.

...