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++ 字符串到双重转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

Bring window to front -gt; raise(),show(),activateWindow() don’t work(把窗户放在前面 -raise(),show(),activateWindow() 不起作用)
How to get a list video capture devices NAMES (web cameras) using Qt (crossplatform)? (C++)(如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像机)?(C++))
How to compile Qt as static(如何将 Qt 编译为静态)
C++ over Qt : Controlling transparency of Labels and Buttons(C++ over Qt:控制标签和按钮的透明度)
How to know when a new USB storage device is connected in Qt?(Qt如何知道新的USB存储设备何时连接?)
What is an event loop in Qt?(Qt 中的事件循环是什么?)