c++ - 将字符串拆分为 2 个 vector 。将字符串转换为浮点类型时遇到问题

标签 c++ std

下面我有一个名为 line 的字符串,它来自一个文件。字符串用逗号分隔,第一部分为字符串 vector ,第二部分为浮点 vector 。之后的任何内容都不会被使用。

第一部分是“文本”,这是正确的。但是第二个显示“248”,而它应该说“1.234”

我需要帮助正确转换它。非常感谢任何帮助,谢谢。

我是编程新手。抱歉任何糟糕的风格。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main ()
{
  string line ("test,1.234,4.3245,5.231");
  string comma (",");
  size_t found;
  size_t found2;
  string round1;
  float round2;
  vector<string> vector1;
  vector<float> vector2;

  // Finds locations of first 2 commas
  found = line.find(comma);
  if (found!=string::npos)

  found2 = line.find(comma,found+1);
  if (found2!=string::npos)





    //Puts data before first comma to round1 (string type)
    for (int a = 0; a < found; a++){
    round1 = round1 += line[a];
    }

    //Puts data after first comma and before second comma to round2 (float type)
    for (int b = found+1; b < found2; b++){
    round2 = round2 += line[b];
    }


    //Puts data to vectors
    vector1.push_back(round1);
    vector2.push_back(round2);


cout << vector1[0] << endl << vector2[0] << endl;


  return 0;
}

最佳答案

你的问题是你将字符添加到浮点值,你不能用这种方式转换它。你实际上在做的是将构成数字的字符的十六进制值相加,如果你查看 ASCII 表,你会注意到 1=49, .=46, 2=50, 3=51, 4=52 .如果你将这 5 加起来,你会得到 248。另外,即使在这种情况下它是错误的:

round2 = round2 += line[b];

应该是:

round2 += line[b];

原因是 += 运算符将等同于:

round2 = round2 + line[b];

所以在它前面添加额外的 round2 = 是没有意义的。

为了做到这一点,请像这样正确使用字符串流:

#include <string>
#include <sstream>

int main()
{
    float f;
    std::stringstream floatStream;
    floatStream << "123.4";
    floatStream >> f;

    return 0;
}

关于c++ - 将字符串拆分为 2 个 vector 。将字符串转换为浮点类型时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12463046/

相关文章:

c++ - c++中 vector 的静态和动态分配有什么区别?

c++ - header 与标准 header 具有相同名称但大小写不同的问题

c++ - std::string 源中宏的使用

C++ std::set 插入时读取无效

c++ - std::unordered_set 中的 KeyEqual 有什么用?

c++ - C++ 中真正的编译时字符串散列

c# - 原生 64 位 dll 的 32 位 Dll 包装器

c++ - gstreamer 将元素添加到通过 gst_parse_launch 创建的管道中

c++ - OpenGL-点云的变色方案

c++ - 从 IBuffer 获取 ComPtr<IStream>