C++字符串转换为双倍

Tim*_*der 32 c++ string double file

通常当我用C++编写任何东西并且我需要将a转换为a时char,int我只需要创建一个int等于char 的新东西.

我用过代码(片段)

 string word;  
 openfile >> word;
 double lol=word;
Run Code Online (Sandbox Code Playgroud)

我收到错误

Code1.cpp cannot convert `std::string' to `double' in initialization 
Run Code Online (Sandbox Code Playgroud)

错误究竟意味着什么?第一个字是数字50.谢谢:)

0x7*_*77D 53

你可以很容易地将char转换为int和反之,因为对于机器而言int和char是相同的,8位,唯一的区别是当它们必须在屏幕上显示时,如果数字是65并且保存为char,然后它会显示'A',如果它保存为int,它将显示65.

随着其他类型的变化,因为它们以不同的方式存储在内存中.在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;
}
Run Code Online (Sandbox Code Playgroud)


Bad*_*Bad 28

#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << stod("  99.999  ") << endl;
}
Run Code Online (Sandbox Code Playgroud)

输出:( 99.999这是双倍的,空格被自动剥离)

由于C++ 11将字符串转换为浮点值(如double),因此可以使用函数:
stof - 将str转换为float
stod - 将str转换为double
stold - 将str转换为long double

由于在问题中也提到了字符串到int的转换,C++ 11中有以下函数:
stoi - 将str转换为int
stol - 将str转换为长
stoul - 将str转换为unsigned long
stoll - 转换str长的
stoull - 将str转换为unsigned long long


tem*_*def 14

问题是C++是一种静态类型的语言,这意味着如果某些东西被声明为a string,那么它就是一个字符串,如果某个东西被声明为a double,那么它就是一个double.与JavaScript或PHP等其他语言不同,无法自动将字符串转换为数字值,因为转换可能没有明确定义.例如,如果您尝试将字符串转换"Hi there!"为a double,则没有有意义的转换.当然,你可以设置double为0.0或NaN,但这几乎肯定会掩盖代码中存在问题的事实.

要解决此问题,请不要将文件内容缓冲到字符串中.相反,只需直接阅读double:

double lol;
openfile >> lol;
Run Code Online (Sandbox Code Playgroud)

这将直接将值读取为实数,如果发生错误将导致流的.fail()方法返回true.例如:

double lol;
openfile >> lol;

if (openfile.fail()) {
    cout << "Couldn't read a double from the file." << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • @Mike:作为一个初学者,当你没有从流中读取,但是有一个字符串时,你需要将它放入一个字符串流中并从中读取. (4认同)
  • 如果您不从流中读取,则需要使用函数来执行转换,例如来自“&lt;stdlib.h&gt;”的“atof()”。 (2认同)

Mat*_*sFG 5

如果您正在读取文件,那么您应该听取给出的建议并将其放入双精度文件中。

另一方面,如果你确实有一个字符串,你可以使用 boost 的lexical_cast

这是一个(非常简单)的例子:

int Foo(std::string anInt)
{
   return lexical_cast<int>(anInt);
}
Run Code Online (Sandbox Code Playgroud)