5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++でParseメソッドが欲しくなった話

Last updated at Posted at 2018-12-04

こんにちはこんばんは。せしまるです。

本日はC++でParseメソッドが欲しくなった話です。

以前C#をやっていた時に先輩に教えてもらったParseとTryParse。

parse.cs
// string型を変換.
int num = int.Parse("7");
double dnum = double.Parse("123.45");

// 変換できるかチェック.
int result = 0;
// int型に変換できないからNG.
if( int.TryParse("100.5", out result)){
    Console.WriteLine("OK");
}else{
    Console.WriteLine("NG");
}

その後C++を初めてから思った。
Parseが欲しい。

現状

現状C++コード内では型変換やチェックは次のようにやってます。

sample.cpp
# include <boost/lexical_cast.hpp>

try{
    int result = boost::lexical_cast<int>("100");
}catch(boost::bad_lexical_cast &ex){
    throw;
}

atoiとかstoiとかあるけど今はlexical_castを使用している。
try~catchまでがながいんじゃ~記述が長くなり少しめんどくさい。

じゃあ使いやすいようにしようか。

実装

とりあえずintに変換するやつだけ。

※追記 2018/12/05
ご指摘を頂いたので修正させて頂きました。

cppparser.hpp
namespace parser{
    // string文字列をintに変換.
    // 変換できなかったらfalse.
    static bool Int_TryParse(const std::string &value, int &result){
        try{
            result = std::stoi(value);
            return true;
        }catch(std::invalid_argument &ex){
            return false;
        }
    }
}
main.cpp
# include "cppparser2.hpp"

int main(){
    int result = 0;
    char array[5] = { '1', '2', '3', '4', '5' };
    std::string str = "9999";

    if(parser::Int_TryParse("100", result)){
        printf("SUCCESS : %d", result);
    }else{
        printf("FAILED.");
    }

    if(parser::Int_TryParse(array, result)){
        printf("SUCCESS : %d", result);
    }else{
        printf("FAILED.");
    }

    if(parser::Int_TryParse(str, result)){
        printf("SUCCESS : %d", result);
    }else{
        printf("FAILED.");
    }

    if(parser::Int_TryParse("a", result)){
        printf("SUCCESS : %d", result);
    }else{
        printf("FAILED.");
    }
}

実行結果

SUCCESS : 100
SUCCESS : 12345
SUCCESS : 9999
FAILED.

入力値の範囲チェック前とかに使えるかな?多分。

本日はここまでです。
ありがとうございました。

5
3
8

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?