# info > A

---
type: CommandReference
command: autosprintf
mode: info
section: ""
source: info
---

## Quick Reference

- `#include "autosprintf.h"` — include the class header
- `using gnu::autosprintf;` — import namespace
- `cerr << autosprintf("format %s", arg);` — print formatted output to stream
- `char* s = autosprintf("format %d", n);` — get C string (must `delete[]`)
- `std::string s = autosprintf("format %s", arg);` — get C++ string
- `autosprintf obj("format", ...);` — create object for later use
- `const char* c_str = obj;` — implicit conversion to `char*`
- `std::string str = obj;` — implicit conversion to `std::string`

## Name

GNU autosprintf — C++ formatted output using printf-like syntax

## Synopsis

cpp
#include "autosprintf.h"
using gnu::autosprintf;

class autosprintf {
public:
    autosprintf(const char *format, ...);
    ~autosprintf();
    operator char*() const;
    operator std::string() const;
};

std::ostream& operator<<(std::ostream& os, const autosprintf& obj);
## Members

- `autosprintf(const char *format, ...)` — constructor; takes a printf-style format string and variable arguments
- `~autosprintf()` — destructor; frees the internal formatted string
- `operator char*()` — returns a freshly allocated copy of the formatted string; caller must free with `delete[]`
- `operator std::string()` — returns a copy of the formatted string as a `std::string` (automatic memory management)
- `operator<<` — outputs the formatted string to the given `std::ostream`

## Examples

cpp
#include <iostream>
#include "autosprintf.h"
using gnu::autosprintf;

int main() {
    const char* filename = "test.c";
    int line = 42;
    const char* errstring = "undefined variable";

    // Using autosprintf with cerr
    std::cerr << autosprintf("syntax error in %s:%d: %s",
                             filename, line, errstring) << std::endl;

    // Alternative with iostream (no autosprintf)
    std::cerr << "syntax error in " << filename << ":" << line << ": "
              << errstring << std::endl;

    // Getting a C string
    char* c_str = autosprintf("value = %f", 3.14);
    // ... use c_str ...
    delete[] c_str;

    // Getting a std::string
    std::string s = autosprintf("count = %d", 100);
    return 0;
}
To link your program, use `libasprintf`. In Autoconf projects, add:

AC_LIB_LINKFLAGS([asprintf])
to `configure.ac` and use the `@LIBASPRINTF@` Makefile variable.

## See Also

- `printf(3)`, `fprintf(3)`, `sprintf(3)` — POSIX formatted output functions
- `std::string` — C++ standard string class
- `std::ostream` — C++ output stream base class
- libasprintf — the library that implements `autosprintf`

## Exit Codes

Not applicable (library class, no exit codes).