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