C++ odpowiednik sprintf?

Wiem, że {[0] } jest odpowiednikiem printf w C++.

Jaki jest odpowiednik C++ sprintf?

 56
Author: Smi, 2011-02-13

6 answers

std::ostringstream

Przykład:

#include <iostream>
#include <sstream> // for ostringstream
#include <string>

int main()
{
  std::string name = "nemo";
  int age = 1000;
  std::ostringstream out;  
  out << "name: " << name << ", age: " << age;
  std::cout << out.str() << '\n';
  return 0;
}

Wyjście:

name: nemo, age: 1000
 49
Author: Vijay Mathew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-28 14:44:28

Użyj Doładuj.Format . MA printf - podobną składnię, bezpieczeństwo typu, Wyniki std::string i wiele innych fajnych rzeczy. Nie wrócisz.

 22
Author: janm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-18 07:48:45

Sprintf działa dobrze w C++.

 14
Author: Steve Rowe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-12-01 19:58:03

Możesz użyć pliku nagłówkowego iomanip do sformatowania strumienia wyjściowego. Sprawdź to !

 7
Author: vinkris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:23

Oto fajna funkcja dla C++ sprintf. Strumienie mogą być brzydkie, jeśli używasz ich zbyt mocno.

std::string string_format(const std::string &fmt, ...) {
    int n, size=100;
    std::string str;
    va_list ap;

    while (1) {
        str.resize(size);
        va_start(ap, fmt);
        int n = vsnprintf(&str[0], size, fmt.c_str(), ap);
        va_end(ap);

        if (n > -1 && n < size)
            return str;
        if (n > -1)
            size = n + 1;
        else
            size *= 2;
    }
}

W C++11 i nowszych, std::string jest gwarantowane, że będzie używać pamięci ciągłej, która kończy się '\0', więc legalne jest rzucanie jej do char * za pomocą &str[0].

 4
Author: Erik Aronesty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-28 11:22:52

Użyj strumienia strun, aby osiągnąć ten sam efekt. Możesz również dołączyć <cstdio> i nadal używać snprintf.

 1
Author: regality,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-25 01:30:07