gpt4 book ai didi

C++:strod() 和 atof() 没有按预期返回 double

转载 作者:行者123 更新时间:2023-12-02 10:01:38 25 4
gpt4 key购买 nike

我正在尝试使用从 .txt 文件中获得的值将字符串转换为 double 值。

我得到的 double 没有小数。我相信这是因为,在 .txt 中,数字的小数点用逗号而不是点分隔。但我不知道如何解决。

这是我的代码的简化:

#include <iostream>
#include <fstream> // read text file
#include <stdlib.h> // strtod, atof

int main() {

std::ifstream readWindData("winddata.txt");

// check that document has been opened correctly
if (!readWindData.is_open()) {
std::cout << "Wind data could not be opened." << std::endl;
return 1;
}

// skip headers of the table
std::string firstLine;
std::getline(readWindData, firstLine);

int numberOfRows = 0; // variable to count rows of the table

// initialise strings that separate each value
std::string time, string u10st, u40st, u60st, u80st, u100st,
u116st, u160st, dir10st, dir60st, dir100st, timeDecst;

// initialise doubles
double u10, u40, u60, u80, u100, u116, u160, dir10, dir60, dir100, timeDec;

std::string nextLine;

// Read strings and turn it into doubles line by line until end
while (readWindData >> time >> u10st >> u40st >> u60st >> u80st >> u100st
>> u116st >> u160st >> dir10st >> dir60st >> dir100st >> timeDecst) {

// try two different functions to turn strings into doubles:
u10 = strtod(u10st.c_str(), NULL);
u40 = atof(u40st.c_str());

// ensure numbers are displaying all their decimals
std::cout.precision(std::numeric_limits<double>::digits10 + 1);

// see what I am getting
std::cout << time << " " << u10st << " " << u10 << " " << u40 << "\n";

std::getline(readWindData, nextLine); // this line skips some crap on the side of some rows

numberOfRows++; // counts rows
}

std::cout << "Number of rows = " << numberOfRows << "\n";
readWindData.close();

return 0;
}

这些是文件的三行:
time (hour) u10(m/s)u40(m/s)u60 (m/s)u80(m/s)u100(m/s)u116(Um/s)u160(m/s)dir10 dir60 dir100         time decimal hours      
00:00 4,25636 7,18414 8,56345 9,75567 10,9667 12,1298 13,8083 110,616 131,652 141,809 0 midnight
00:10 4,54607 7,40763 8,62832 9,91782 11,2024 12,2694 14,1229 114,551 133,624 142,565 0,166666667

这些是使用上述代码输出的那些行:
(提醒,我 std::cout 时间(字符串),u10st(字符串),u10(双),u40(双))。
00:00 4,25636 4 7
00:10 4,54607 4 7

关于如何将 4,25636 字符串读入双 4.25636 的任何想法?文件太长,无法修改。

最佳答案

为避免弄乱全局语言环境,您只需替换 ,.在调用 strtod() 之前

    std::replace(u10st.begin(), u10st.end(), ',', '.');
u10 = strtod(u10st.c_str(), nullptr);

但在上面显示的程序中,您也可以从 ifstream 中读取直接进入 double使用运算符 >> , 如果您使用 comma 的语言环境是小数分隔符。
    readWindData.imbue(std::locale("de_DE.UTF-8")); // or fr, nl, ru, etc.

double u10, u40, u60, u80, u100, u116, u160, dir10, dir60, dir100, timeDec;

while (readWindData >> time >> u10 >> u40 >> u60 >> u80 >> u100
>> u116 >> u160 >> dir10 >> dir60 >> dir100 >> timeDec) {

Live demo

关于C++:strod() 和 atof() 没有按预期返回 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62302120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com