Newer
Older
Skill_semi_sample / SS2301-02 / ss2301_02.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <set>
#include <fstream>

const std::set<std::string> LOWERCASE_WORDS = {
    "a", "an", "and", "the", "in", "on", "at", "by", "for", 
    "with", "about", "against", "between", "into", "through", 
    "during", "before", "after"
};

std::string toLower(const std::string& str) {
    std::string result = str;
    for(char& c : result) {
        c = std::tolower(c);
    }
    return result;
}

std::string capitalize(const std::string& input) {
    std::stringstream ss(input);
    std::string word, result;

    bool isFirstWord = true;
    while (ss >> word) {
        if (!isFirstWord) {
            result += " ";
        }
        if (isFirstWord || LOWERCASE_WORDS.find(toLower(word)) == LOWERCASE_WORDS.end()) {
            word[0] = std::toupper(word[0]);
            for (size_t i = 1; i < word.size(); ++i) {
                word[i] = std::tolower(word[i]);
            }
        } else {
            word = toLower(word);
        }
        result += word;
        isFirstWord = false;
    }

    return result;
}

int main(int argc, char* argv[]) {
    std::string input;

    // 引数が与えられた場合、それをファイル名として読み込む
    if (argc == 2) {
        std::ifstream file(argv[1]);
        if (!file) {
            std::cerr << "Error: Could not open file: " << argv[1] << std::endl;
            return 1;
        }
        std::getline(file, input, '\0');  // ファイルの内容を全て読み込む
        file.close();
    } else {
        std::cout << "Enter the text to capitalize (end with Enter): ";
        std::getline(std::cin, input);
    }

    std::string output = capitalize(input);
    std::cout << output << std::endl;

    return 0;
}