1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[備忘録]std::stoiは"文字列を数値に変換"だと思ってた

Posted at

”数値に変換できなかったら例外"ではない

普通に使うと↓

実装
#include<iostream>

int main(){
    std::string str1 = "100";
    std::string str2 = "test";
    int num1 = 0;
    int num2 = 0;
    try {
        num1 = std::stoi(str1);
    } catch(...) {
        num1 = 0;
    }
    try{
        num2 = std::stoi(str2);
    } catch(...) {
        num2 = 0;
    }
    printf("%d\n",num1);
    printf("%d\n",num2);
}
実行結果
100
0

先頭が数字であれば例外は投げない

先頭が数字で、以降文字だったとしても例外は投げない

実装
#include<iostream>

int main(){
    std::string str1 = "test100";
    std::string str2 = "100test";
    int num1 = 0;
    int num2 = 0;
    try{
        num1 = std::stoi(str1);
    } catch(...) {
        num1 = 0;
    }
    try{
        num2 = std::stoi(str2);
    } catch (...) {
        num2 = 0;
    }
    printf("%d\n",num1);
    printf("%d\n",num2);
}
実行結果
0
100

先頭が数字かつ以降文字であれば失敗or例外処理したい

変換後の数値の桁数元の文字列の長さが一致しなければ失敗にする

判別関数
bool judgeConvert(int ConversionNum,std::string originStr) {
    bool judge;
    if (std::to_string(ConversionNum).length() == originStr.length()) {
        judge = true;
    } else {
        judge = false;
    }
    return judge;
}
main関数
int main(){
    std::string str1 = "100";
    std::string str2 = "100test";
    int num1 = 0;
    int num2 = 0;
    try {
        num1 = std::stoi(str1);
        if (judgeConvert(num1,str1) == false) {
            num1 = 0;
        }
    } catch(...) {
        num1 = 0;
    }
    try {
        num2 = std::stoi(str2);
        if (judgeConvert(num2,str2) == false) {
            num2 = 0;
        }
    } catch(...) {
        num2 = 0;
    }
    printf("%d\n",num1);
    printf("%d\n",num2);
}
実行結果
100
0

今後の課題

ほかの例外ケースもありそうなので、もう少し検討したい

1
1
2

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?