0

folks! I've been struggling with this problem for some time and so far I haven't found any solution to it.

In the code below I initialize a string with a number. Then I use std::istringstream to load the test string content into a double. Then I cout both variables.

#include <string>
#include <sstream>
#include <iostream>

std::istringstream instr;

void main()
{
    using std::cout;
    using std::endl;
    using std::string;

    string test = "888.4834966";
    instr.str(test);

    double number;
    instr >> number;

    cout << "String test:\t" << test << endl;
    cout << "Double number:\t" << number << endl << endl;
    system("pause");
}

When I run .exe it looks like this:

String test: 888.4834966
Double number 888.483
Press any key to continue . . .

The string has more digits and it looks like std::istringstream loaded only 6 of 10. How can I load all the string into the double variable?

Santus Westil
  • 43
  • 1
  • 5

3 Answers3

5
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>

std::istringstream instr;

int main()
{
    using std::cout;
    using std::endl;
    using std::string;

    string test = "888.4834966";
    instr.str(test);

    double number;
    instr >> number;

    cout << "String test:\t" << test << endl;
    cout << "Double number:\t" << std::setprecision(12) << number << endl << endl;
    system("pause");

    return 0;
}

It reads all of the digits, they're just not all displayed. You can use std::setprecision (found in iomanip) to correct this. Also note that void main is not standard you should use int main (and return 0 from it).

Borgleader
  • 15,826
  • 5
  • 46
  • 62
1

The precision of your output probably just isn't showing all of the data in number. See this link for how to format your output precision.

sedavidw
  • 11,116
  • 13
  • 61
  • 95
1

Your double value is 888.4834966 but when you use:

cout << "Double number:\t" << number << endl << endl;

It uses a default precision for double, to set it manually use:

cout << "Double number:\t" << std::setprecision(10) << number << endl << endl;
Kostia
  • 271
  • 1
  • 9