问题:使用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++ - C++ std::regex_replace rgx和fmt参数为科学计数法的指数添加前导零?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41774407/

10-13 08:23