okay lets say i have the following String and inside it there is a decimal number.
How do I translate it to binary number. I know its easier to declare an integer
but its for a project that I have to use a string.Also how can i check if it is
a number.
1 2 3
//how would i make this a binary ?
std::string instruction = "3";
You can use this ToNumber template function that uses the std::istringstream class to convert a string to a number. As I understood, it always tries to convert the number, for example, if you have an expression like this: "231a2" it returns the number 231, which means that this functions seems to return the number until it doesn't find a letter or something else different from a number. If you insert "a123", it returns 0.
1 2 3 4 5 6 7
template <class N> N ToNumber(std::string string_number)
{
N number;
std::istringstream iss(string_number);
iss >> number;
return number;
}
I have written this function a time ago to convert from decimal to binary numbers, which uses another function that I wrote (ReverseString)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//converts a integer number to a binary number represented by a string.
//this function uses 2 other functions: ToString() and reverse_string()
std::string DecimalToBinary(int decimal)
{
int coefficient = -1, numerator = decimal;
std::string binary = "";
while(coefficient != 0)
{
binary += ToString(numerator % 2);//ToString() defined above
coefficient = numerator / 2;
numerator = coefficient;
}
return ReverseString(binary);//defined below
}
Okay so Now I am able to check if its a number thank u very much . however still not sure how to convert to a binary string since the above function zwilu gave me std::string DecimalToBinary(int decimal) takes an int as an argument and i needed to take a string.
I Aslo have another fucntion: