从字符串 c++ 中获取所有数字
Get all numbers from string c++
我知道这个问题被问了好几次,但没有一个答案符合我的需要。
所以我有这个字符串
九月=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>
这正是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,
- 如何获取一个数字的前3位
- 获取 2D 数组 c++ 中的所有数字对
- 获取第 n 个最大数字
- 获取 2 个数字之间的差异百分比
- 在获取从文件到矢量的每一行之后,数字将被更改或销毁
- QChar 如果 'isDigit()' 则获取数字值
- 从(排序的)数字列表中获取数字范围
- 有没有更简单的方法可以从用户那里获取三个数字并按升序打印它们?
- 如何以正确的时区从XTS索引中获取数字时间?
- 如何获取数字的更改
- 获取具有特定距离的键值对数组中的最大数字
- 有没有一种更快的方法,从特定的数字池中获取随机数
- 如何仅从字符串中获取数字
- 如何从大数字中获取指定的数字?
- 从数组指针中获取怪异的数字
- 获取数字小数部分的最佳方法
- 获取数字最左边两个位的值的最便宜的方法是什么?
- 使用数字列表和算术运算获取目标数字
- 从字符串 c++ 中获取所有数字
- 遍历 std::string 时如何获取没有数字的字符?