Invoice++
Loading...
Searching...
No Matches
utils.h
Go to the documentation of this file.
1#ifndef UTILS_H
2#define UTILS_H
3
4#include <iconv.h>
5#include <stdexcept>
6#include <vector>
7#include <sstream>
8
11inline std::string UTF8toISO8859_1(const std::string& utf8_str) {
12 const iconv_t conv_desc = iconv_open("ISO-8859-1//TRANSLIT", "UTF-8");
13 if (conv_desc == reinterpret_cast<iconv_t>(-1)) {
14 throw std::runtime_error("iconv_open failed");
15 }
16
17 size_t in_bytes_left = utf8_str.size();
18 size_t out_bytes_left = in_bytes_left; // ISO-8859-1 won't be larger than UTF-8
19 std::vector<char> output_buffer(out_bytes_left);
20 char* in_buf = const_cast<char*>(utf8_str.data());
21 char* out_buf = output_buffer.data();
22
23 if (iconv(conv_desc, &in_buf, &in_bytes_left, &out_buf, &out_bytes_left) == static_cast<size_t>(-1)) {
24 iconv_close(conv_desc);
25 throw std::runtime_error("iconv conversion failed");
26 }
27
28 std::string result(output_buffer.data(), output_buffer.size() - out_bytes_left);
29 iconv_close(conv_desc);
30 return result;
31}
32
35template < typename Type > std::string to_str (const Type & t)
36{
37 std::ostringstream os;
38 os << t;
39 return os.str ();
40}
41
42#endif //UTILS_H
std::string to_str(const Type &t)
converts various datatypes to string using ostringstream
Definition utils.h:35
std::string UTF8toISO8859_1(const std::string &utf8_str)
converts a UTF8 string to ISO8859-1 / ANSI using iconv
Definition utils.h:11