tinycodinglm / polyglot /polyglot-0003.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 16)
d517dc9 verified
|
Raw History Blame Contribute Delete
1.76 kB
opencode trace
System You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations.

You are an expert software engineer. You give correct, idiomatic, runnable code with brief explanations.

User

How do I count lines, words, characters and bytes of a UTF-8 text file? Show me the C++ version.

Assistant

In C++17 there is no Unicode-aware string: std::string::size() is bytes. Count UTF-8 lead bytes (any byte that is not a 10xxxxxx continuation) to get code points.

cpp
#include <cassert>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

int main() {
    const std::string text = "Olá mundo! Ação, coração.\nSegunda linha: Straße, 你好.\n";
    {
        std::ofstream out("sample.txt", std::ios::binary);
        out << text;
    }
    std::ifstream in("sample.txt", std::ios::binary);
    std::ostringstream ss;
    ss << in.rdbuf();
    const std::string data = ss.str();
    const long bytes = static_cast<long>(data.size());
    long chars = 0;
    for (unsigned char c : data) {
        if ((c & 0xC0) != 0x80) ++chars;  // count lead bytes only
    }
    long words = 0, lines = 0;
    { std::istringstream ws(data); std::string w; while (ws >> w) ++words; }
    { std::istringstream ls(data); std::string l; while (std::getline(ls, l)) ++lines; }
    std::cout << "lines=" << lines << " words=" << words
              << " chars=" << chars << " bytes=" << bytes << "\n";
    assert(lines == 2 && words == 8);
    assert(bytes > chars);
    return 0;
}