C++ 字符串到双重转换

C++ string to double conversion(C++ 字符串到双重转换)
本文介绍了C++ 字符串到双重转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我使用了代码(片段)

 string word;  
 openfile >> word;
 double lol=word;

我收到错误

Code1.cpp cannot convert `std::string' to `double' in initialization 

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

What does the error mean exactly? The first word is the number 50. Thanks :)

推荐答案

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

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.

对于其他类型,情况会发生变化,因为它们在内存中的存储方式不同.C 中有一个标准函数可以让你轻松地从字符串转换为双精度,它是 atof.(你需要包含 stdlib.h)

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)

#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;
}

这篇关于C++ 字符串到双重转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)