在C 中的push_back之前,将字符串转换为浮点

Converting a string to a float before push_back in C++

本文关键字:字符串 转换 之前 中的 push back      更新时间:2023-10-16

我有大量的CSV线,我要分解逐条线,通过逗号分裂,将这些令牌放在向量中。

这是我处理该句子中最后两个项目的小代码段:

//token for parser
        string token;
        //turn into a string stream
        istringstream ss(line);
        //ye olde vector to put things in
        std::vector<float> lineContainer;
        while(getline(ss, token, ','))
        {
            lineContainer.push_back(::atof(token));
        }

当我尝试编译时,我会得到以下内容:

Error: cannot convert 'std::string' to "const char*' for argument '1' to 'double atof(const char*)'.

换句话说,将字符串转换为浮子是不可以的,至少我是如何做的。

如何将此数据类型转换为浮点?我认为这是直接的,但是我对C 的经验不足(我保证在C#中更好),并且还没有抓住所有以其他语言为理所当然的事情的细微差别。

token是类型std::stringatof将C-string或const char*指针指向nul终止的字符阵列。

lineContainer.push_back(::atof(token.c_str()));

http://www.cplusplus.com/reference/string/string/c_str/