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?
#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).
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.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.