Skip to content

Instantly share code, notes, and snippets.

@klmr
Created June 25, 2012 11:06
Show Gist options
  • Save klmr/2987985 to your computer and use it in GitHub Desktop.
Save klmr/2987985 to your computer and use it in GitHub Desktop.
Wide-character handling in C++
#include <cstdlib>
#include <iostream>
#include <locale>
#include <stdexcept>
int main() {
std::string line;
std::string input;
std::size_t bytes = 0;
std::size_t characters = 0;
try {
std::locale::global(std::locale(""));
}
catch (std::runtime_error const& e) {
std::cout << e.what() << "\n";
return 1;
}
std::cout << "Using locale: " << std::locale().name() << "\n";
while (getline(std::cin, line)) {
input += line + "\n";
bytes += line.length();
for (
std::size_t i = 0;
i < line.length();
i+= std::mblen(line.c_str() + i, line.length() - i)
)
++characters;
}
std::cout << input;
std::cout << bytes << " bytes " << characters << " characters\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment