这个代码出了什么问题?我需要把字符串转换成浮点数

What is wrong with this code? I need to convert string into float

本文关键字:字符串 转换 浮点数 代码 问题 什么      更新时间:2023-10-16

此代码有什么问题?我需要把字符串转换成浮点数。m2在m2中存在错误。长度

#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; 
}

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

好吧,那么使用字符串流将字符串中的数字提取到向量中怎么样?

#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);
}

您的代码可能有太多错误,无法解释每一点。我就是这么做的:

float v2;
std::istringstream iss("1 23 45 6");
while(iss >> v2) {
std::cout << v2 << std::endl;
}

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

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

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

一旦你把它放进循环中,你会有很多数字,但比你预期的要多:
*第一次迭代,它会以"1 23 45 6"=>1开始
*第二次迭代,以"23 45 6"=>23开始
>第三次迭代,再次以"23 46"=>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("%.2fn", v2);
}

这是在线演示。

真正的c++替代方案:

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

使用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; 
}