C++ C++;将循环中的字符串转换为双精度字符串

C++ C++;将循环中的字符串转换为双精度字符串,c++,type-conversion,double,C++,Type Conversion,Double,我试图将数字转换成循环中的字符串,但立即将它们转换为双精度,这样就可以将3个数字相加,并用于获得平均值。这是我的代码: string name; double num = 0, many = 0, total = 0, value = 0; inputFile.open("Rainfall.txt"); for (int count = 1; count <= 6; count++) { inputFile >> name; if (count == 1

我试图将数字转换成循环中的字符串,但立即将它们转换为双精度,这样就可以将3个数字相加,并用于获得平均值。这是我的代码:

string name;
double num = 0, many = 0, total = 0, value = 0;

inputFile.open("Rainfall.txt");


for (int count = 1; count <= 6; count++)
{
    inputFile >> name;

    if (count == 1 || count == 3 || count == 5)
    {

        continue;

    }

    num = stod(name);

    num += total;


}

cout << total << endl;
字符串名;
double num=0,many=0,total=0,value=0;
inputFile.open(“rainment.txt”);
对于(int count=1;count>name;
如果(计数=1 | |计数=3 | |计数=5)
{
继续;
}
num=stod(名称);
num+=总数;
}

cout假设输入文件结构保持完整(不清理输入),这里有一个稍微好一点的方法并且,
std::stod
将在无法转换为双精度的输入上严重失败。您只需同时将给定的月降雨量和月降雨量总和读入相应的变量类型。如果您将整个内容放入while循环中,它将继续读取您的输入,直到它到达文件末尾或流有错误为止错误

#include <iostream>
#include <fstream>

int main()
{
    double total(0.0);
    std::ifstream inputFile("Rainfall.txt");
    if (inputFile.is_open())
    {
        std::string month;
        double rain(0.0);
        while(inputFile >> month >> rain)
        {
            total += rain;
        }
        inputFile.close();  ///< technically not necessary
    }

    std::cout << "total rainfall " << total << std::endl;

    return 0;
}
#包括
#包括
int main()
{
双倍总数(0.0);
std::ifstream输入文件(“rainment.txt”);
if(inputFile.is_open())
{
std::字符串月份;
双雨(0.0);
同时(输入文件>>月>>雨)
{
总数+=降雨量;
}
inputFile.close();//<
}

std::cout total一开始是0,您从未修改过它。您想将num变量添加到total中。请尝试total+=num。另外,您应该在调试器中逐步检查代码以了解发生了什么。好的@AnonMail谢谢,我不敢相信这段时间我唯一的错误是我执行num+=total,而不是您所说的。谢谢您,我必须这样做我试过了所有的方法,但没有试过。谢谢。你也可以在循环中每次读取字符串和双精度,只需忽略字符串的值,而不是将字符串读入双精度,然后在需要时继续计数。
继续。
@StephenDocy你能给我提供代码吗?我这样做是因为我无法计算请确保退出
inputFile.close()
是不必要的,您可以将您的
is\u open
检查反转为提前返回,从而节省一定程度的缩进。@很简单,我知道fstream是一个合适的RAII对象,但我个人认为关闭流并刷新输入缓冲区是一个很好的做法。我的编码标准鼓励单点返回,但您的观点是正确的。