C++ 字符串到双重转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4754011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ string to double conversion
提问by TimeCoder
Usually when I write anything in C++ and I need to convert a char
into an int
I simply make a new int
equal to the char.
通常,当我用 C++ 编写任何东西并且需要将 a 转换char
为 an 时,int
我只需创建一个int
等于 char的新值。
I used the code(snippet)
我使用了代码(片段)
string word;
openfile >> word;
double lol=word;
I receive the error that
我收到的错误是
Code1.cpp cannot convert `std::string' to `double' in initialization
What does the error mean exactly? The first word is the number 50. Thanks :)
错误究竟是什么意思?第一个词是数字 50。谢谢:)
回答by 0x77D
You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.
您可以轻松地将 char 转换为 int,反之亦然,因为对于机器而言,int 和 char 是相同的,8 位,唯一的区别是它们必须显示在屏幕上,如果数字为 65 并保存为字符,然后它会显示'A',如果它被保存为一个int,它会显示65。
With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)
对于其他类型,事情会发生变化,因为它们在内存中的存储方式不同。C 中有一个标准函数可以让你轻松地从字符串转换为双精度,它是 atof。(你需要包含 stdlib.h)
#include <stdlib.h>
int main()
{
string word;
openfile >> word;
double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
previously (the function requires it)*/
return 0;
}
回答by Bad
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << stod(" 99.999 ") << endl;
}
Output: 99.999
(which is double, whitespace was automatically stripped)
输出:(99.999
这是双倍,空格被自动剥离)
Since C++11 converting string to floating-point values (like double) is available with functions:
stof- convert str to a float
stod- convert str to a double
stold- convert str to a long double
由于 C++11 将字符串转换为浮点值(如 double)可用于以下函数:
stof- 将 str 转换为浮点数
stod- 将 str 转换为 double
stold- 将 str 转换为 long double
As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi- convert str to an int
stol- convert str to a long
stoul- convert str to an unsigned long
stoll- convert str to a long long
stoull- convert str to an unsigned long long
由于问题中还提到了将字符串转换为 int,因此 C++11 中有以下函数:
stoi- convert str to an int
stol- convert str to a long
stoul- convert str to an unsigned long
stoll- convert str to a long long
stoull- 将 str 转换为 unsigned long long
回答by templatetypedef
The problem is that C++ is a statically-typed language, meaning that if something is declared as a string
, it's a string, and if something is declared as a double
, it's a double. Unlike other languages like JavaScript or PHP, there is no way to automatically convert from a string to a numeric value because the conversion might not be well-defined. For example, if you try converting the string "Hi there!"
to a double
, there's no meaningful conversion. Sure, you couldjust set the double
to 0.0 or NaN, but this would almost certainly be masking the fact that there's a problem in the code.
问题在于 C++ 是一种静态类型语言,这意味着如果将某些内容声明为 a string
,则它是一个字符串,如果某些内容声明为 a double
,则它是一个双精度值。与 JavaScript 或 PHP 等其他语言不同,无法自动从字符串转换为数值,因为转换可能没有明确定义。例如,如果您尝试将字符串转换"Hi there!"
为 a double
,则没有有意义的转换。当然,您可以将 设置double
为 0.0 或 NaN,但这几乎肯定会掩盖代码中存在问题的事实。
To fix this, don't buffer the file contents into a string. Instead, just read directly into the double
:
要解决此问题,请不要将文件内容缓冲到字符串中。相反,只需直接读入double
:
double lol;
openfile >> lol;
This reads the value directly as a real number, and if an error occurs will cause the stream's .fail()
method to return true. For example:
这会将值直接作为实数读取,如果发生错误将导致流的.fail()
方法返回 true。例如:
double lol;
openfile >> lol;
if (openfile.fail()) {
cout << "Couldn't read a double from the file." << endl;
}
回答by MatiasFG
If you are reading from a file then you should hear the advice given and just put it into a double.
如果你正在阅读一个文件,那么你应该听到给出的建议,然后把它变成一个替身。
On the other hand, if you do have, say, a string you could use boost's lexical_cast.
另一方面,如果你确实有一个字符串,你可以使用 boost 的lexical_cast。
Here is a (very simple) example:
这是一个(非常简单的)示例:
int Foo(std::string anInt)
{
return lexical_cast<int>(anInt);
}
回答by Rodolfo Martinez
The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.
下面的程序说明了 C++ 解决转换的方法(不是经典的 C)。请注意,其目的是能够使用 iostream 提供的相同格式化工具,如精度、填充字符、填充、十六进制和操纵器等。
Compile and run this program, then study it. It is simple
编译并运行这个程序,然后研究它。很简单
#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;
int main()
{
// Converting the content of a char array or a string to a double variable
double d;
string S;
S = "4.5";
istringstream(S) >> d;
cout << "\nThe value of the double variable d is " << d << endl;
istringstream("9.87654") >> d;
cout << "\nNow the value of the double variable d is " << d << endl;
// Converting a double to string with formatting restrictions
double D=3.771234567;
ostringstream Q;
Q.fill('#');
Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
S = Q.str(); // formatted converted double is now in string
cout << "\nThe value of the string variable S is " << S << endl;
return 0;
}
Prof. Martinez
马丁内斯教授
回答by EleetGeek
Coversion from string to double can be achieved by using the 'strtod()' function from the library 'stdlib.h'
可以使用库“stdlib.h”中的“strtod()”函数实现从字符串到双精度的转换
#include <iostream>
#include <stdlib.h>
int main ()
{
std::string data="20.9";
double value = strtod(data.c_str(), NULL);
std::cout<<value<<'\n';
return 0;
}
回答by ausercomment
#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}
or
或者
//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
n+=( (s[x]- (s[x]<='9' ? '0':'0'+7) ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}