我需要将double存储为字符串.我知道我可以使用,printf如果我想显示它,但我只是想将它存储在一个字符串变量中,以便我以后可以将它存储在地图中(作为值,而不是键).
我有一个数据库填充了以下双打:
1.60000000000000000000000000000000000e+01
Run Code Online (Sandbox Code Playgroud)
有人知道如何在C++中将这样的数字转换为double吗?
是否有"标准"方式来做这类事情?或者我必须自己动手?
现在我正在做这样的事情:
#include <string>
#include <sstream>
int main() {
std::string s("1.60000000000000000000000000000000000e+01");
std::istringstream iss(s);
double d;
iss >> d;
d += 10.303030;
std::cout << d << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
我一直在努力寻找这一天的解决方案!你可能会把它标记为重新发布,但我真正想要的是一个没有使用boost lexical cast的解决方案.传统的C++方式很棒.我尝试了这段代码,但它返回了一组乱码数字和字母.
string line;
double lineconverted;
istringstream buffer(line);
lineconverted;
buffer >> lineconverted;
Run Code Online (Sandbox Code Playgroud)
我也试过这个,但它总是返回0.
stringstream convert(line);
if ( !(convert >> lineconverted) ) {
lineconverted = 0;
}
Run Code Online (Sandbox Code Playgroud)
提前致谢 :)
编辑:对于我使用的第一个解决方案(乱码)..这是一个快照

我无法使用该atof()功能。我只希望用户输入值(以十进制数字的形式),直到他们输入'|',然后打破循环。我希望这些值最初以字符串形式读取,然后转换为双精度,因为我在过去使用此输入法时发现过,如果输入数字“ 124”,则会中断循环,因为“ 124”是“ |”的代码 字符
我四处张望,发现了atof()将strings 转换为doubles 的函数,但是当我尝试转换时,得到消息
“不存在从std :: string到const char的合适转换函数”。
我似乎无法弄清楚为什么会这样。
void distance_vector(){
double total = 0.0;
double mean = 0.0;
string input = " ";
double conversion = 0.0;
vector <double> a;
while (cin >> input && input.compare("|") != 0 ){
conversion = atof(input);
a.push_back(conversion);
}
keep_window_open();
}
Run Code Online (Sandbox Code Playgroud) 我想创建一个程序,读取包含两个数字和一个运算符的字符串,并打印出结果.它不断显示算术运算符的错误.例如,我如何将两个字符串一起添加?
int main()
{
string number1;
string number2;
string operation;
string answer;
cout << "Enter numbers with respective operations";
cout << "number 1";
cin >> number1;
cout << "number2";
cin >> number2;
cout << "operation";
cin >> operation;
if (operation == "+")
{
answer = number1 + number2;
cout << "the sum is " << answer << endl;
}
else if (operation == "-")
{
answer = number1 - number2;
cout << "the difference is " << answer << endl; …Run Code Online (Sandbox Code Playgroud) 我正在尝试从c ++中的文本获取值(所有十进制数字)。但我有一个问题,我无法解决
#include "pch.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main()
{
std::ifstream infile("C:\\thefile.txt");
float a, b;
while (infile >> a >> b)
{
// process pair (a,b)
}
std::cout << a << " " << b;
}
Run Code Online (Sandbox Code Playgroud)
thefile.txt:
34.123456789 77.987654321
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,
a = 34.1235
b = 77.9877
Run Code Online (Sandbox Code Playgroud)
但我想要
a = 34.123456789
b = 77.987654321
Run Code Online (Sandbox Code Playgroud)
我该怎么办?
编辑:我不想打印出a和b。我只希望他们得到确切的值。