从字符串 c++ 中获取所有数字

Get all numbers from string c++

本文关键字:数字 获取 字符串 c++      更新时间:2023-10-16

我知道这个问题被问了好几次,但没有一个答案符合我的需要。
所以我有这个字符串

九月=1, V_Batt=7.40, I_Batt=-

559.63, V_SA=7.20, I_SA=-0.55, I_MB=500.25, V_5v=4.95, I_5v=446.20, V_3v=3.28, I_3v=3.45, S=0, T_Batt=25.24, T_SA1=22.95, T_SA2=-4.86

我想获取"="符号后的所有数字并创建一个新字符串,例如

1,7.40,559.63,7.20,0.55,500.25,4.95,446.20,3.28,3.45,0,25.24,22.95,4.68

谁能帮我解决问题。我使用了字符串流,但我的输出全部为 0谢谢

基于对实际需求的正确理解,我会做与我最初建议完全不同的事情。在这种情况下,我同意 Stephen Webb 的观点,即正则表达式可能是正确的方法,尽管我对使用正确的正则表达式以及如何使用它存在分歧(尽管后者可能与我养成的习惯一样多(。

#include <regex>
#include <iostream>
#include <string>
int main()
{
    using iter = std::regex_token_iterator<std::string::const_iterator>;
    std::string s = "Sep=1, V_Batt=7.40, I_Batt=-559.63, V_SA=7.20,
                    " I_SA=-0.55, I_MB=500.25, V_5v=4.95, I_5v=446.20,"
                    " V_3v=3.28, I_3v=3.45, S=0, T_Batt=25.24, T_SA1=22.95," 
                    " T_SA2=-4.86";
    std::regex re(R"#([A-Z][^=]*=([-.d]+))#");
    auto begin = iter(s.begin(), s.end(), re, 1);
    iter end;
    for (auto i = begin; i!= end; ++i)
        std::cout << *i << ", ";
    std::cout << 'n';
}

结果:

1, 7.40, -559.63, 7.20, -0.55, 500.25, 4.95,

446.20, 3.28, 3.45, 0, 25.24, 22.95, -4.86,

如果参数的数量及其顺序已知,则可以像这样使用 snprintf:

char str[100];
int Sep=1;
double V_Batt = 7.40, I_Batt = 559.63;// etc ...
snprintf(str, 100, "%d,%.2f,%.2f", Sep, V_Batt, I_Batt); //etc...
// str = 1,7.40,559.63

使用 fopen(( 函数打开文件。它返回 File* 变量。当然,如果已经可以使用您的字符,请跳过此步骤。使用此 File 变量来获取每个字符,比如说,通过 fgetc((。检查获得的char变量的内容并用它制作你想要的东西,最终在你的新字符串中插入一些逗号,根据需要<</p>

div class="answers>

这正是std::regex_iterator的用途。

#include <regex>
#include <iostream>
#include <string>
int main()
{
    const std::string s = "Sep=1, V_Batt=7.40, I_Batt=-559.63, V_SA=7.20, I_SA=-0.55, I_MB=500.25, V_5v=4.95, I_5v=446.20, V_3v=3.28, I_3v=3.45, S=0, T_Batt=25.24, T_SA1=22.95, T_SA2=-4.86";
    std::regex re("[-\d\.]+");
    auto words_begin = std::sregex_iterator(s.begin(), s.end(), re);
    auto words_end = std::sregex_iterator();
    for (std::sregex_iterator i = words_begin; i != words_end; ++i)
        std::cout << (*i).str() << ',';
    std::cout << "n";
}

上述完整程序的输出是这样的。

1,7.40,-

559.63,7.20,-0.55,500.25,5,4.95,5,446.20,3,3.28,3,3.45,0,25.24,1,22.95,2,-4.86,