最简单的方法是根据冒号将字符串分成两个值

时间:2015-02-04 07:32:53

标签: c++

我有一个字符串,表示为:

a = <string>:<float_value>

我以string的形式阅读了整个内容,并且我试图在独立的string中捕获string部分,并在独立float_value中捕获float部分{1}}。完成此任务的最简单方法是什么?

4 个答案:

答案 0 :(得分:4)

使用string::findstof

size_t colon_pos = a.find(':');
string str = a.substr(0, colon_pos);
float f = stof(a.substr(colon_pos+1));

答案 1 :(得分:1)

可能是sscanf?

sscanf("a = %s:%f",&s_string,&f_float);

答案 2 :(得分:0)

像这样:

std::string a = "asda:123";

size_t colon_pos = a.rfind(":");

if (colon_pos == std::string::npos) {
    // Error, invalid string
}

std::string the_string = a.substr(0, colon_pos);
try {
    float the_float = std::stof(a.substr(colon_pos + 1));
} catch (const std::invalid_argument & exc) {
    // Error, cannot convert
} catch (const std::out_of_range & exc) {
    // Error, value out of range
}

请注意使用rfind,因此即使您的字符串部分包含冒号也应该正常工作。

如果你没有C ++ 11,而不是std::stof,你可以使用:

float the_float = 0.0;
std::string the_float_str = a.substr(colon_pos + 1);
std::stringstream stream;
stream << the_float_str;
stream >> the_float;

答案 3 :(得分:0)

正如其中一条评论所暗示的那样,最简洁的方法是使用std::getline(inputstream,line,delimiter)。示例代码为:

std::string input;//your input string with tag:value information
std::stringstream ss(input);
std::string item;
std::vector<std::string> output;
while (std::getline(ss, item, ':'))
   output.push_back(item);

然后在output向量中,您可以根据需要获得物品/代币。根据应用程序的其余代码,您可能希望将其包装在函数中或按原样使用。

例如我在这样的函数中使用它:

std::vector<std::string> &split(
    std::string &input,
    std::vector<std::string> &output,
    char delim)
{
    std::stringstream ss(input);
    std::string item;
    while (std::getline(ss,item,delim))
        output.push_back(item);
    return output;
}

请注意,如果输入字符串中有多个delimiter,则此代码会将所有这些代码分开。您需要在问题中更加具体,以便我可以调整答案。

为了将您的项目转换为浮动,您可以查看此示例:

// stof example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stof

int main ()
{
  std::string orbits ("686.97 365.24");
  std::string::size_type sz;     // alias of size_t

  float mars = std::stof (orbits,&sz);
  float earth = std::stof (orbits.substr(sz));
  std::cout << "One martian year takes " << (mars/earth) << " Earth years.\n";
  return 0;
}

请注意,您需要启用c ++ 11标准。该示例直接来自here