-8

这段代码有什么问题?我需要将字符串转换为浮点数。m2 在m2.length中有错误

#include <iostream>
#include <string>
#include <cstdlib>
#include <sstream>
using namespace std;

int main()
{
    float v2;
    char *m2 = "1 23 45 6";
    for (int i = 0; i < m2.length(); i++) //to convert every element in m2 into float
    {
        v2 = atof(&m2[i]);
    }
    printf("%.2f", v2);

    system("pause");
    return 0; 
}
4

4 回答 4

3

我需要转换数组中的每个元素,以便可以存储它们以进行操作

好的,那么您如何使用字符串流将字符串中的数字提取到向量中?

#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

int main()
{
    std::string input = "1 23 45 6";
    std::stringstream ss(input);
    std::istream_iterator<double> end;
    std::vector<double> output(std::istream_iterator<double>(ss), end);
}
于 2015-04-25T11:49:41.300 回答
1

您的代码也可能有问题,无法解释每一点。我就是这样做的:

float v2;
std::istringstream iss("1 23 45 6");
while(iss >> v2) {
    std::cout << v2 << std::endl;
}
于 2015-04-25T11:49:35.120 回答
0

使用string代替char*, 使事情变得更容易一些。

要将给定字符串转换为数值,请使用stringstreamatof()

快速解决您的问题:

#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main()
{
    vector<float> myFloats;
    string m("1. 2.23 45 6456    72.8  46..");

    // First of parse given string and separate char groups that serve as a number
    // => only consider 0-9 and '.'
    if(m.size() == 0)
        return 1;

    string charGroup;
    for(int i=0; i<m.length(); i++)
    {
        if((isdigit(m.at(i)) || m.at(i) == '.'))
        {
            charGroup += m.at(i);
            if(i == m.length() - 1 && !charGroup.empty())
            {
                // in case given group is a numerical value
                myFloats.push_back((float) atof(charGroup.c_str()));

                // prepare for next group
                charGroup.clear();
            }
        }
        else if(!charGroup.empty())
        {
            if(m.at(i) == ' ')
            {
                // in case given group is a numerical value
                myFloats.push_back((float) atof(charGroup.c_str()));

                // prepare for next group
                charGroup.clear();
            }
            else charGroup.clear();
        }
    }

    // Print float values here
    if(!myFloats.empty())
    {
        cout << "Floats: ";
        for(int i=0; i<myFloats.size(); i++)
            cout << myFloats.at(i) << ", ";
    }

    getchar();
    return 0; 
}
于 2015-04-25T12:54:06.010 回答
0

逐步分析,从错误中学习:

length()首先,字符数组没有成员函数,因此您应该定义string m2="...";以便代码编译。

不幸的是,您的代码只会打印一个数字:最后一个。为什么 ?因为你printf()在循环之外。

一旦你把它放在循环中,你会有很多数字,但比你预期的要多:
*第一次迭代,它以“1 23 45 6”=> 1
*第二个“23 45”开始6" => 23
* 第三次迭代 "23 45 6" => 23 再次!
* 第四次迭代 "3 45 6" => 3 (你预料到了吗?)

所以你必须从一个数字跳到下一个数字。因此,您可以使用函数搜索下一个空格,而不是递增find_first_of()

for (int i = 0; i < m2.length(); i=m2.find_first_of(' ', i+1)) // jump to the next space
{
    v2 = atof(&m2[i]);
    printf("%.2f\n", v2);
}

这里是在线演示

真正的 c++ 替代品:

看看πάντα ῥεῖ的解决方案:这就是我们在 C++ 中的做法

于 2015-04-25T12:10:41.423 回答