The conversion i wrote of hexadecimal to decimal number is working but get some little bit unexpected result.
Expected result : HEX number "0000000F" and Output is in Decimal "15"
In my case
1] if "0000000F" is HEX value and it's conversion is "1532"
2] if "000000FF" is HEX value and it's conversion is "25532"
I am not sure what part of programming is wrong ? every time I get "32" After any decimal value result. Can Anyone suggest how to fix this issue ?
#include <iostream>
using namespace std ;
#include <sstream>
int wmain() {
while(1)
{
int binNumber ;
unsigned int decimal;
string hexString = "0000000F"; //you may or may not add 0x before
stringstream myStream;
myStream <<hex <<hexString;
myStream >>binNumber;
cout <<binNumber <<decimal;
//return 0;
}
}
If you look at the first parts of your outputs, you will notice that they are correct.
But here:
cout <<binNumber <<decimal;
you're printing decimal immediately afterwards, and it is uninitialised.
Remove it.
(On a related note, don't declare variables that you think you might need at some point in the future. Many bugs lurk down that way.)
// Correct code
#include <iostream>
using namespace std ;
#include <sstream>
int wmain() {
while(1)
{
int binNumber ;
// unsigned int dummy=0;
string hexString = "000000FF"; //you may or may not add 0x before
stringstream myStream;
myStream <<hex <<hexString;
myStream >>binNumber;
cout <<binNumber ;
//return 0;
}
}
Related
// See the code below and help me why i did not getting the right result. Or suggest any other C++ function to convert a C-string like "$567,789,675.89" into long double
long double mstold( char s[] )
{
int len = strlen(s);
long double cash;
int n=0;
char amount[ 100 ];
for( int i=0; i<len; i++) // for copying the passed C-String into another C-string
{
amount[n] = s[i];
n++;
if( s[i] == '$' || s[i] == ',') // Because the C-String has been passed in format: "$567,789,564.987"
n--;
}
cash = _atold( amount ); // This does not gives the right result
return cash;
}
Use strtold() function, since _atold() is a non standard function. I am posting the code which works in compiler explorer. You were not terminating amount array with '\0'. Perhaps that's the reason _atold not worked.
#include <cstdlib>
#include <iostream>
#include <cstring>
using namespace std;
long double mstold(const char* s)
{
int len = strlen(s);
long double cash;
int n = 0;
char* amount = new char[len+1];
for (int i = 0; i<len; i++) // for copying the passed C-String into another C-string
{
amount[n] = s[i];
n++;
if (s[i] == '$' || s[i] == ',') // Because the C-String has been passed in format: "$567,789,564.987"
n--;
}
amount[n] = '\0';
cash = strtold(amount, NULL); // This does not gives the right result
delete[] amount;
return cash;
}
int main()
{
long double cash = mstold("$567,789,675.89");
std::cout << cash << std::endl;
}
First note. Please do not use C-Style strings. In C++ we use std::string. Anyway, also C-style strings will do and can be converted automatically.
Then, for newbies it is the best to transform the input monetary-string to a number-string with just one decimal digit and then use function stold for conversion. You may read here about it.
But in the real C++ world, you would do 2 things:
use dedicated C++ facilities
use localization
Unfortunately this is a rather complex topic and you need a while to understand.
You need to read about the localization library. Here you will learn about 2 major concepts:
locales
facets
In general textual representation of dates, monetary values or number formats are governed by regional or cultural conventions. All this properties are contained in a std::locale object.
But the std::locale does not offer much functionality. The real localization facilities are offered in the form of facets. And a std::locale encapsulates several facets. And one of them is about the monetary formatting.
You really can do many things with that and in the end get fully customized behaviour. But, as said, not that easy to understand.
I will use the std::money_get class in my below example.
Please note. This will convert your number into units, without a fraction. In financial calculations we basically should not use fractions, because double or even long double cannot store all "reaal" values". Please read about this as well.
Anyway. I will show you an example how such a monetary value would be converted in C++. You maybe shocked by the complexity, but flexibility has its price . . .
Please see:
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
#include <locale>
#include <sstream>
int main() {
// Input String
char valueAsCString[] = "$567,789,675.89";
// Put it in an istringstream for formatted extraction
std::istringstream iss{ valueAsCString };
// Assume US currency format (On Posix machines, please use "en-US") and set it for the stream
std::locale myLocale("en_US");
iss.imbue(myLocale);
// Assume that everthing is good
std::ios_base::iostate ioError{ std::ios_base::goodbit };
// Here we will get the value in UNITS, so without a fraction!!!
long double value{};
// Parse the money string and get the result
std::use_facet<std::money_get<char>>(myLocale).get(std::istreambuf_iterator<char>(iss), {}, false, iss, ioError, value);
// Check Error state
iss.setstate(ioError);
if (iss)
// Show result
std::cout << std::setprecision(std::numeric_limits<long double>::digits10 + 1) << std::setw(25) << value / 100 << '\n';
else
std::cerr << "\nError during conversion\n";
}
I have an input file which I'm reading in with the basic myFile >> variable since I know the format and the format will always be correct. The file I'm reading in is formatted as instruction <num> <num> and to make >> work, I'm reading everything in as a string. If I have 3 variables, one to take in each piece of the line, how can I then turn string <1> (for example) into int 1? I know the string's first and last characters are brackets which need to be removed, then I could cast to an int, but I'm new to C++ and would like some insight on the best method of doing this (finding and removing the <>, then casting to int)
use stringstream
#include <string>
#include <sstream>
#include <iostream>
int main() {
std::string str = "<1>";
int value;
std::stringstream ss(str);
char c;
ss >> c >> value >> c;
std::cout << value;
}
First to get the middle character out you can just do char myChar = inputString.at(1);. Then you can do int myInt = (int)myChar;
Even if you remove the <> characters, your still importing the file content into a string using >> so you still need to cast it to an int. If you have only 1 value, you can follow what Nicholas Callahan wrote in the previous answer, but if you have multiple characters you want to read as int, you dont have a choice but to cast.
You can also resort to sscanf.
#include <cstdio>
#include <iostream>
#include <string>
int main()
{
std::string str = "<1234>";
int value;
sscanf(str.c_str(), "<%d>", &value);
std::cout << value << std::endl;
}
1)double d = 1.234567899;
Convert this number to string with 8 decimal places without truncation.
So,expected output is "1.23456789", truncating last 9.
and
2)if d = 1.2345699;
so Solution should not append 0 upto 8th decimal place.expected output "1.2345699".
I have tried many solutions,ended up with stringstream c++ class. 2nd problem is solved but first one still persist.
Is there any way to achieve the output?
Thanks in advance.
If you want to truncate part of the string representation without rounding, you need to do that manually:
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <limits>
int main()
{
std::stringstream s;
double d = 1.234567899;
// print it into sstream using maximum precision
s << std::fixed << std::setprecision(std::numeric_limits<double>::digits10) << 1.234567899;
std::string res = s.str();
// Now the res contains something like 1.234567899000000
// so truncate 9000000000 by hand
size_t dotIndex = res.find(".");
std::string final_res = res.substr(0, dotIndex + 9);
std::cout << final_res << std::endl;
return 0;
}
Would you be served by first Flooring the double to the required decimals?
If so, have a look at http://www.cplusplus.com/forum/beginner/3600/
Truncating exactly as you want:
sprintf(str, "%1.10f", d);
memset(str+10, 0x00, 1);
I have an integer 1 and i want to display it as a character '1' in C++. So far I have only managed to convert it from say integer 65 to character 'A'.
How do you stop this ?
int theDigit = 1;
char ch = theDigit+'0';
This works because it's guaranteed1 that the sequence of characters '0'...'9' is contiguous, so if you add your number to '0' you get the corresponding character. Obviously this works only for single digits (if theDigit is e.g. 20 you'll get an unrelated character), if you need to convert to a string a whole number you'll need snprintf (in C) or string streams (in C++).
C++11, [lex.charset] ΒΆ3:
In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.
By the way, I suppose that they didn't mandate contiguity also in the alphabetical characters just because of EBCDIC.
Use the stringstream.
int blah = 356;
stringstream ss;
string text;
ss << blah;
ss >> text;
Now text contains "356"(without quotes). Make sure to include the header files and use the namespace if you are going to copy my code:
#include <sstream> //For stringstream
#include <string>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
int i = 3;
char buffer [25];
itoa (i, buffer, 10);
printf ("Integer: %s\n",buffer);
Integer: 3
You did just ask about printing an integer, so the really simple c++ answer is:
#include <iostream>
int main()
{
int value = 1;
std::cout << value << endl;
return 0;
}
i have a unicode mapping stored in a file.
like this line below with tab delimited.
a 0B85 0 0B85
second column is a unicode character. i want to convert that to 0x0B85 which is to be stored in int variable.
how to do it?
You've asked for C++, so here is the canonical C++ solution using streams:
#include <iostream>
int main()
{
int p;
std::cin >> std::hex >> p;
std::cout << "Got " << p << std::endl;
return 0;
}
You can substitute std::cin for a string-stream if that's required in your case.
You could use strtol, which can parse numbers into longs, which you can then assign to your int. strtol can parse numbers with any radix from 2 to 36 (i.e. any radix that can be represented with alphanumeric charaters).
For example:
#include <cstdlib>
using namespace std;
char *token;
...
// assign data from your file to token
...
char *err; // points to location of error, or final '\0' if no error.
int x = strtol(token, &err, 16); // convert hex string to int