Append int to std::string

TL;DR operator+= is a class member function in class string, while operator+ is a template function. The standard class template<typename CharT> basic_string<CharT> has overloaded function basic_string& operator+=(CharT), and string is just basic_string<char>. As values that fits in a lower type can be automatically cast into that type, in expression s += 2, the 2 is … Read more

Concatenating strings doesn’t work as expected [closed]

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar: std::string c = “hello” + “world”; This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do … Read more

C++: how to get fprintf results as a std::string w/o sprintf

Here’s the idiom I like for making functionality identical to ‘sprintf’, but returning a std::string, and immune to buffer overflow problems. This code is part of an open source project that I’m writing (BSD license), so everybody feel free to use this as you wish. #include <string> #include <cstdarg> #include <vector> #include <string> std::string format … Read more

Padding stl strings in C++

std::setw (setwidth) manipulator std::cout << std::setw (10) << 77 << std::endl; or std::cout << std::setw (10) << “hi!” << std::endl; outputs padded 77 and “hi!”. if you need result as string use instance of std::stringstream instead std::cout object. ps: responsible header file <iomanip>

Explicit copy constructor

The explicit copy constructor means that the copy constructor will not be called implicitly, which is what happens in the expression: CustomString s = CustomString(“test”); This expression literally means: create a temporary CustomString using the constructor that takes a const char*. Implicitly call the copy constructor of CustomString to copy from that temporary into s. … Read more

convert a char* to std::string

std::string has a constructor for this: const char *s = “Hello, World!”; std::string str(s); Note that this construct deep copies the character list at s and s should not be nullptr, or else behavior is undefined.

Is it possible to use std::string in a constexpr?

As of C++20, yes, but only if the std::string is destroyed by the end of constant evaluation. So while your example will still not compile, something like this will: constexpr std::size_t n = std::string(“hello, world”).size(); However, as of C++17, you can use string_view: constexpr std::string_view sv = “hello, world”; A string_view is a string-like object … Read more