gpt4 book ai didi

C++ std::regex_replace rgx 和 fmt 参数以在科学记数法中为指数添加前导零?

转载 作者:太空宇宙 更新时间:2023-11-04 13:06:56 25 4
gpt4 key购买 nike

问题:使用 VS 2015 编译器时,sprintf 仅以科学记数法打印指数的两个字符。我想像 VS 2012 编译器那样打印三个字符。我的解决方案是使用 std::regex_replace 函数对格式化字符串进行后处理。我需要为 rgx 模式和 fmt 替换格式字符串输入什么以向指数添加前导零,但不更改字符串 s 中的任何其他内容?

// http://www.cplusplus.com/reference/regex/regex_replace/

#include <cstdlib>
#include <iostream>
#include <ostream>
#include <regex>
#include <stdio.h>
#include <string>

void addLeadingZeroToExponentsFailsToWork() {
// If exponents have only 2 characters, then add a leading zero.
std::string s("X: 5.600000e-05 dm2; Y: 3.466654e+07 dm2; Z: 5.430000e-08 dm2;");
std::regex rgx("(-?\\d+\\.\\d+e[-|+])(\\d{2}\\s+)");
std::string fmt("$1 0$2");
std::string res = std::regex_replace(s, rgx, fmt);
std::cout << res << std::endl << std::endl;
system("pause");
}

// fmt("$10$2") ==> X: 05 dm2; Y: 07 dm2; Z: 08 dm2;
// fmt("$1 0$2") ==> X: 05.600000e- 005 dm2; Y: 03.466654e+ 007 dm2; Z: 05.430000e- 008 dm2;
// What rgx and fmt? ==> X: 5.600000e-005 dm2; Y: 3.466654e+007 dm2; Z: 5.430000e-008 dm2;

// Below is my updated function based on the accepted answer from Laszlo:

#define BELL "\007"

void addLeadingZeroToExponents() {
// If exponents have only 2 characters, then add a leading zero.
const std::string s("X: -5.600000e-15 dm2; Y: +3.466654e+07 dm2; Z: 5.430000e-08 dm2;");
const std::regex rgx("([-+]?\\d+\\.\\d+e[-+])(\\d{2}\\s+)");
// Inserting a zero directly does not seem to be possible without a positive look-behind assertion,
// which C++11 does not have. So first insert some character (BELL) that will never appear in
// the input string, and then replace that character with a zero.
const std::string fmt("$1" BELL "$2");
const std::string res = std::regex_replace(std::regex_replace(s, rgx, fmt), std::regex(BELL), "0");
std::cout << res << std::endl << std::endl;
system("pause");
}

int main()
{
addLeadingZeroToExponents();
return 0;
}

最佳答案

嗯,它不是那么优雅,但它会产生所需的输出。它需要一个字符,该字符不会出现在输入字符串的其他位置。

#define BELL "\007"

void addLeadingZeroToExponentsBell() {
// If exponents have only 2 characters, then add a leading zero.
std::string s("X: 5.600000e-05 dm2; Y: 3.466654e+07 dm2; Z: 5.430000e-08 dm2;");
std::regex rgx("([-|+]?\\d+\\.\\d+e[-|+])(\\d{2}\\s+)");

std::string fmt("$1" BELL "$2");
std::string res = std::regex_replace(std::regex_replace(s, rgx, fmt), std::regex(BELL), "0");

std::cout << res << std::endl << std::endl;
system("pause");
}

关于C++ std::regex_replace rgx 和 fmt 参数以在科学记数法中为指数添加前导零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41774407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com