convert from string to double fails to convert as expected - c++11

I am trying to convert "21898.99" to a string I but keep on getting 21898.990000000002 but I am expecting 21898.99
#include <cstdlib>
#include <boost/lexical_cast.hpp>
#include <limits>
#include <iostream>
int main()
{
double d1 = std::strtod("21898.99", nullptr);
long double d2 = std::strtold("21898.99", nullptr);
float d3 = std::strtof("21898.99", nullptr);
double d4 = atof("21898.99");
double d5 = boost::lexical_cast<double>("21898.99");
double d6;
sscanf_s("21898.99", "%lf", &d6);
double d7;
sscanf_s("21898.99", "%lg", &d7);
std::istringstream ss("21898.99");
double d8 = 0.0;
ss >> d8;
typedef std::numeric_limits< double > dbl;
std::cout.precision(dbl::max_digits10);
std::cout << d1 << "\n";
std::cout << d2 << "\n";
std::cout << d3 << "\n";
std::cout << d4 << "\n";
std::cout << d5 << "\n";
std::cout << d6 << "\n";
std::cout << d7 << "\n";
std::cout << d8 << "\n";
}
Output:
21898.990000000002
21898.990000000002
21898.990234375
21898.990000000002
21898.990000000002
21898.990000000002
21898.990000000002
21898.990000000002
Windows 10 version 10.0.14939.0
Visual Studio 2017 15.9.0, C++ 19.15.26732.1
Windows SDK 10.0.17134.0
I tried on a centos machine with gcc and this call works, but the others also fail.
long double d2 = std::strtold("21898.99", nullptr);
since it returns 21898.99

This is the expected behavior for floating point numbers; some values are not exactly representable.

Related

Why do uint8_t arrays behave different to uint16_t array when using begin() and end()?

I am trying to understand why the following code snippet behaves different for the uint16_t array than the uint8_t array.
I would expect memory addresses to be printed for both cases. What am I missing?
#include <iostream>
int main()
{
uint16_t a[3] = { 65, 66, 67 };
uint8_t b[3] = { 88, 89, 90 };
std::cout << std::begin(a) << " " << std::end(a) << std::endl;
std::cout << std::begin(b) << " " << std::end(b) << std::endl;
}
Sample output:
0x7ffee64ca990 0x7ffee64ca996
XYZ

I initialize char *str1 = nullptr and output to the screen... But when i want output to other variable i receive empty screen.. Why is it happening?

#include <iostream>
#include <cstring>
int main()
{
const char *str = "Hello world";
char *str1 = nullptr;
std::cout << str << std::endl; // when i output to screan i see hello world
std::cout << str1 << std::endl; // when i output to scream i sen nothing
str1 = new char[strlen(str) + 1];
strcpy(str1, str);
std::cout << str << std::endl; // when i output to scream again i sen nothing
std::cout << str1 << std::endl; // The same
}

How to compose and form the binary literals, for example through the conversion from decimal in C++11 / C++14?

int main() {
int x = 3613;
std::cout << "x= " << x << std::endl;
std::string xBin = std::bitset<16>(x).to_string();
std::cout << xBin << std::endl;
unsigned long xDecimal = std::bitset<16>(xBin).to_ulong();
std::cout << xDecimal << std::endl;
std::cout << std::endl << std::endl;
int b01 = 0b11001;
std::cout << "b01= " << b01 << std::endl;
int b02 = 0b1010;
std::cout << "b02= " << b02 << std::endl;
int b03 = b01 + b02;
std::cout << "int b03 = b01 + b02 = " << b03 << std::endl;
return 0;
}
Output:
x= 3613
0000111000011101
3613
b01= 25
b02= 10
int b03 = b01 + b02 = 35
With binary literals we can do normal arithmetic operations, while with the strings obtained with std::bitset<> this is not possible.
So...the question is: how to "compose" the binary literals, for example through the conversion from decimal to binary as obtained using std::bitset<> ?
Looking forward to your kind help. Marco
You shouldn't operate on bitsets by converting them to string and back - that's missing the point of bitsets... Instead you operate on them by using binary operators: &, |, ^, ... (just like you would on usual integers).
std::cout << std::bitset<3>(4) << " or "
<< std::bitset<3>(2) << " = "
<< (std::bitset<3>(4) | std::bitset<3>(2)) << std::endl;
Prints: 100 or 010 = 110
You can find all operators on wiki: http://en.cppreference.com/w/cpp/utility/bitset

no exception guarantee when rounding using nearbyint()

I understand that nearbyint allows me to round integers without throwing exceptions. It is possible to use feclearexcept to check for errors or see if rounding took place (which will always be the case for nearbyint).
Can anyone show me an example of when an exception would have been thrown which has been avoided by using nearbyint?
Here is an example of the normal use of the function:
#include <cfenv>
#include <cmath>
#include <iostream>
void test(const char* title, int round_mode)
{
std::feclearexcept(FE_ALL_EXCEPT);
std::fesetround(round_mode);
std::cout << title << std::endl;
std::cout << "nearbyint(2.5) = " << std::nearbyint(2.5) << std::endl;
std::cout << "nearbyint(-2.5) = " << std::nearbyint(-2.5) << std::endl;
std::cout << "FE_INEXACT = " << std::boolalpha << (std::fetestexcept(FE_INEXACT) != 0) << std::endl << std::endl; // This will always be true.
}
#define test(mode) test(#mode, mode)
int main()
{
#ifdef FE_DOWNWARD
test(FE_DOWNWARD);
#endif
#ifdef FE_TONEAREST
test(FE_TONEAREST);
#endif
#ifdef FE_TOWARDZERO
test(FE_TOWARDZERO);
#endif
#ifdef FE_UPWARD
test(FE_UPWARD);
#endif
}

How to use SetConsoleTextAttribute C++

I have searched countless forums and websites but I can't seem to find the answer. I'm trying to use SetConsoleTextAttribute but it only affects the text. How can I affect the whole screen like the command color 1f would? My code is:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <wincon.h>
using namespace std;
int main()
{
SetConsoleTitle("C++ CALCULATOR"); // Title of window
int x; // Decision
int a; // First Number
int b; // Second Number
int c; // Answer
HANDLE Con;
Con = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(Con, BACKGROUND_BLUE | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
cout << "CALCULATOR" << endl << endl;
cout << "1:ADDITION" << endl << "2:SUBTRACTION" << endl << "3:MULTIPLICATION";
cout << endl << "4:DIVISION" << endl << "5:EXIT" << endl;
cin >> x;
switch (x)
{
case 1: // Addition code
cout << endl << "ADDITION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a + b;
cout << endl << "ANSWER:" << c;
break;
case 2: // Subtraction code
cout << endl << "SUBTRACTION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a - b;
cout << endl << "ANSWER:" << c;
break;
case 3: // Multiplication code
cout << endl << "MULTIPLICATION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a * b;
cout << endl << "ANSWER:" << c;
break;
case 4: // Division code
cout << endl << "DIVISION" << endl << "FIRST NUMBER:";
cin >> a;
cout << endl << "SECOND NUMBER:";
cin >> b;
c = a / b;
cout << endl << "ANSWER:" << c;
break;
case 5: // Exit code
return 0;
}
}
This solution relies on these WinAPI functions and structures:
GetConsoleScreenBufferInfo to get screen dimensions
FillConsoleOutputAttribute to fill screen with an attribute
CONSOLE_SCREEN_BUFFER_INFO structure to store screen information
The code is as follows:
HANDLE hCon;
CONSOLE_SCREEN_BUFFER_INFO csbiScreenInfo;
COORD coordStart = { 0, 0 }; // Screen coordinate for upper left
DWORD dwNumWritten = 0; // Holds # of cells written to
// by FillConsoleOutputAttribute
DWORD dwScrSize;
WORD wAttributes = BACKGROUND_BLUE | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
// Get the screen buffer information including size and position of window
if (!GetConsoleScreenBufferInfo(hCon, &csbiScreenInfo))
{
// Put error handling here
return 1;
}
// Calculate number of cells on screen from screen size
dwScrSize = csbiScreenInfo.dwMaximumWindowSize.X * csbiScreenInfo.dwMaximumWindowSize.Y;
// Fill the screen with the specified attribute
FillConsoleOutputAttribute(hCon, wAttributes, dwScrSize, coordStart, &dwNumWritten);
// Set attribute for newly written text
SetConsoleTextAttribute(hCon, wAttributes);
The inline comments should be enough to understand the basics of what is going with the supplied documentation links. We get the screen size with GetConsoleScreenBufferInfo and use that to determine the number of cells on the screen to update with a new attribute using FillConsoleOutputAttribute . We then use SetConsoleTextAttribute to ensure that all new text that gets printed matches the attribute we used to color the entire console screen.
For brevity I have left off the error check for the calls to FillConsoleOutputAttribute and SetConsoleTextAttribute. I put a stub for the error handling for GetConsoleScreenBufferInfo . I leave it as an exercise for the original poster to add appropriate error handling if they so choose.
SetConsoleTextAttribute changes the attribute for new characters that you write to the console, but doesn't affect existing contents of the console.
If you want to change the attributes for existing characters already being displayed on the console, use WriteConsoleOutputAttribute instead.

Resources