'How to store integer value from int variable in char variable?

int d = names.size() - 2;
    char c = char(d);

return names[0] + ", " + names[1] + " and " + c + " others like this";

Now, I have to return the number of people stored in variable "d" as a single string but as "d" is an integer, it cannot be directly added. So, what should I do to store the value of "d" as a string or char to add in the return string?



Solution 1:[1]

std::ostringstream will help you a lot here, as you can simply write values of different types (e.g. strings and numbers) to it.

In the example below I use it together with the <fmt> library, but you could use the <format> library instead (C++20, MSVC), or just write to oss as you would write to std::cout.

[Demo]

#include <fmt/core.h>
#include <iostream>  // cout
#include <sstream>  // ostringstream
#include <string>
#include <vector>

auto f(const std::vector<std::string>& names) {
    if (names.size() >= 2) {
        int d = names.size() - 2;
        std::ostringstream oss{};
        oss << fmt::format("{}, {} and {} others like this", names[0], names[1], d);
        return oss.str();
    }
    return std::string{};
}

int main() {
    std::vector<std::string> names{ "Anne", "Brian", "Charlize", "Daniel" };
    std::cout << f(names);
}

// Outputs:
//
//   Anne, Brian and 2 others like this

Solution 2:[2]

In C++, there are two different types of string: char arrays and std::string.

std::string [Easiest approach.]

std::strings behave similarly to strings in other programming languages (they can be concatenated, ). To convert an int to an std::string, use std::to_string(val) (see https://en.cppreference.com/w/cpp/string/basic_string/to_string).

I would avoid using C-style strings here as they have a fixed size and need to be deleted manually.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rturrado
Solution 2 Cannon