You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++是否有类似JavaScript的模板字符串?求简洁遍历目录的for循环写法

Great question! Let's break this down into two parts for clarity:

C++ Equivalent to JavaScript Template Strings

C++ does have features that mirror JavaScript's template literals, though the syntax and availability depend on which C++ standard you're using.

C++20 and Later: std::format (Closest Match)

Starting with C20, the standard library introduced std::format—a clean, type-safe way to format strings that’s very similar to JS template strings. Here’s how you’d rewrite your JavaScript example in C20:

#include <iostream>
#include <format>

int main() {
    for (int i = 0; i < 10; ++i) {
        std::cout << std::format("Liftoff in {} seconds\n", i);
    }
    return 0;
}

The {} placeholders work just like ${} in JS, and std::format handles type conversion automatically, making it safer than old C-style formatting.

Pre-C++20 Workarounds

If you’re stuck on an older C++ standard, you have a few solid options:

1. std::stringstream

This is the standard library’s type-safe alternative for pre-C++20 code:

#include <iostream>
#include <sstream>

int main() {
    for (int i = 0; i < 10; ++i) {
        std::stringstream ss;
        ss << "Liftoff in " << i << " seconds\n";
        std::cout << ss.str();
    }
    return 0;
}

It’s a bit more verbose than std::format, but it avoids the pitfalls of C-style printf.

2. C-Style snprintf

If you prefer a syntax closer to JS template literals (though less type-safe), you can use snprintf:

#include <iostream>
#include <cstdio>

int main() {
    char buffer[100];
    for (int i = 0; i < 10; ++i) {
        std::snprintf(buffer, sizeof(buffer), "Liftoff in %d seconds\n", i);
        std::cout << buffer;
    }
    return 0;
}

Just be careful with buffer sizes to avoid overflow!

3. Third-Party Libraries (e.g., fmtlib)

Before std::format was standardized, the fmt library (now the basis for C20’s std::format) was a popular choice. It uses identical syntax to std::format and works with older C versions.

Concisely Iterating Over Multiple Directories with a For Loop

For clean directory traversal, C++17 introduced the <filesystem> library, which simplifies working with file systems. Here’s a concise example that iterates over a list of directories and prints all their top-level files:

#include <iostream>
#include <filesystem>
#include <vector>

namespace fs = std::filesystem;

int main() {
    // List of directories to iterate over
    std::vector<fs::path> directories = {"./dir1", "./dir2", "./path/to/another/dir"};

    // Loop through each directory
    for (const auto& dir : directories) {
        if (!fs::exists(dir) || !fs::is_directory(dir)) {
            std::cerr << "Directory does not exist or is not a directory: " << dir << "\n";
            continue;
        }

        std::cout << "Files in " << dir << ":\n";
        // Iterate over entries in the directory
        for (const auto& entry : fs::directory_iterator(dir)) {
            if (entry.is_regular_file()) {
                std::cout << "  " << entry.path().filename() << "\n";
            }
        }
    }
    return 0;
}

If you need to traverse directories recursively (including subdirectories), replace fs::directory_iterator with fs::recursive_directory_iterator.

Quick Notes:

  • Ensure your compiler supports C++17 or later to use <filesystem>. Some older compilers may require linking against a separate filesystem library (e.g., -lstdc++fs with GCC).
  • This approach is type-safe and integrates seamlessly with other C++ standard library features, making it far cleaner than manual directory traversal with C-style APIs.

内容的提问来源于stack exchange,提问作者msalla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 18:37:51