【Cocos2d-x】CSVを使う

【Cocos2d-x】CSVを使う

アプリを作る際に初期データを用意することがあると思います。今回は初期データをCSVで作成した際のCSV読み込みについてです。

CSVが以下のような時、

[user.csv]
id,name,place
1,川井,神奈川
2,加藤,青森
3,沢田,愛知

bool HelloWorld::init()
{
    //略...
    
    //データの読み込み
    ValueVector users;
    std::string csvStr = FileUtils::getInstance()->getStringFromFile("user.csv");
    ValueVector balls = this->split(csvStr, "\n");
    ValueVector keys = this->split(balls.at(0).asString(), ",");
    for (int i = 1; i < (int)balls.size(); i ++) {
        ValueMap userParams;
        ValueVector params = this->split(balls.at(i).asString(), ",");
        for (int j = 0; j < (int)params.size(); j ++) {
            userParams[keys.at(j).asString()] = params.at(j).asString();
        }
        users.push_back(Value(userParams));
        log("push");
    }
    
    //データの確認
    for (int i = 0; i < (int)users.size(); i ++) {
        ValueMap user = users.at(i).asValueMap();
        std::string userId = user.at("id").asString();
        std::string name = user.at("name").asString();
        std::string place = user.at("place").asString();
        log("%s, %s, %s, %d", userId.c_str(), name.c_str(), place.c_str(), (int)users.size());
    }

    //略...
}

ValueVector HelloWorld::split(const std::string &str, const std::string &delim){
    ValueVector res;
    size_t current = 0, found;
    while((found = str.find_first_of(delim, current)) != std::string::npos){
        res.push_back(Value(std::string(str, current, found - current)));
        current = found + 1;
    }
    res.push_back(Value(std::string(str, current, str.size() - current)));
    return res;
}

これでcsvが読み込めました。

今回は以上です。

  • このエントリーをはてなブックマークに追加
  • Pocket

コメント一覧

  1. エラー より:

    //データの確認
    for (int i = 0; i < (int)users.size(); i ++) {
    ValueMap user = users.at(i).asValueMap();
    std::string userId = user.at("id").asString();
    std::string name = user.at("name").asString();
    std::string place = user.at("place").asString();
    log("%s, %s, %s, %d", userId.c_str(), name.c_str(), place.c_str(), (int)users.size());
    }

    この部分でエラーが出ました。

    std::string userId = user.at("id").asString();までは大丈夫なのですが、
    それ以降の

    std::string name = user.at("name").asString(); 

    この一文を足すと、Fatal signal 11 (SIGSEGV)、とエラーが出て動きません。
    cocos2d-xのバージョンは3.5、eclipse、csvファイルの中身は同じ、コードは丸コピペで起きました。

    • buildman より:

      コメントありがとうございます。
      こちら、Eclipseで試しましたが、問題なく動きました。

      一度、記事中コード14行目の、
      keys.at(j).asString()とparams.at(j).asString()のログを出力してみてください。
      そこはどのようなログが出力されるでしょうか。

この記事へのコメントはこちら

メールアドレスは公開されませんのでご安心ください。
また、* が付いている欄は必須項目となりますので、必ずご記入をお願いします。

内容に問題なければ、下記の「コメント送信」ボタンを押してください。

CAPTCHA