Search code examples
pythonc++python-3.xfmt

What is the C++ equivalent of the % or .format operator in Python?


I am quite new to C++ and I am writing a program that needs an operator that does the same thing as the Python % operator. Is there any equivalent in C++?


Solution

  • C++ has several ways to do IO, mostly for historical reasons. Whichever style your project uses should be used consistently.

    1. C-style IO: printf, sprintf, etc.
    #include <cstdio>
    
    int main () {
      const char *name = "world";
      // other specifiers for int, float, formatting conventions are avialble
      printf("Hello, %s\n", name); 
    }
    
    1. C++ style IO: iostreams
    #include <iostream>
    
    int main() {
      std::string name = "world";
      std::cout << "Hello, " << name << std::endl;
    }
    
    1. Libraries/C++20 std::format:

    Pre C++20 quite a few people have provided their own formatting libraries. One of the better ones is {fmt}. C++ adopted this kind of formatting as [std::format][2]

    #include <format>
    #include <iostream>
    #include <string>
    
    int main() {
      std::string name = "world";
      std::cout << std::format("Hello, {}", name) << std::endl;
    }
    

    Notice that format produces format-strings, so it works with both ways to do IO, and/or other custom approaches, but if you use C-style IO it would probably be mostly weird to layer std::format on top, where the printf specifier would also work.