卒研で文字列から数値に変換する時にstoi()を使っています。しかし、これが曲者で、毎回コンパイルエラーを出してしまいます。
[bash] terminate called after throwing an instance of ‘std::invalid_argument’ what(): stoi [/bash]環境によってメッセージは異なりますが、だいたいこんな感じです。
さて、これはなんだと言われたら、例外処理を書いてねーぞっていうメッセージらしいです。
[blogcard url=”https://github.com/CtrlGit/cpp-tutorial/blob/master/doc/xx-ExceptionHandling.md”]
ということで、例外処理を書いてあげればOK。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
using namespace std; | |
int main(int argc, char const *argv[]) { | |
string s = "。оО(。´•ㅅ•。)Оо。"; //いつでもミクサはあなたを見ている | |
try{ | |
int a = stoi(s); | |
cout << a << endl; | |
} | |
catch(const std::invalid_argument& e){ | |
cout << "invalid argument" << endl; | |
} | |
catch(const std::out_of_range& e){ | |
cout << "Out of range" <<endl; | |
} | |
return 0; | |
} |
参考:[blogcard url=”https://qiita.com/koara-local/items/3d1b077764e16171b6dd”]
invalid_argumentは「これ数値じゃねえぞ」って感じで、out_of_rangeは「型の最大値超えたんだが?」という感じだと思います。
ただ、ちゃんと文字列が数値だけだと例外処理書いてなくても動くんですよね。
このへん、コンパイラの気持ちがよくわからない。