LoginSignup
12

More than 5 years have passed since last update.

C++で文字列が数字かチェックする

Last updated at Posted at 2017-04-29

stringからintに変換

stringをintに変えるには、stoi()が使える。

hoge.cpp
#include <iostream>
using namespace std;

int main()
{
    string hoge = "123";
    string hoge2 = "123a";
    string hoge3 = "a123";
    cout << stoi(hoge) << endl;
    cout << stoi(hoge2) << endl;
    // cout << stoi(hoge3) << endl;
}
hoge.cppの結果
123
123

数字ではない文字から始まっているとエラーになる。なので、数字かチェックするのには使えない。

追記:コメントをいただいて、stoi()のエラーを捕捉するのがいい方法だとわかりました。下記のcheck_init()だと、intを超える数字の場合でもチェックが通りますが、stoi()でout_of_rangeエラーになります。

文字列が数字かチェック

参考:文字列が数字で構成されているかを判定する

hoge.cpp
#include <iostream>
#include <cctype>
#include <algorithm>

int main()
{
    using std::string;
    string hoge = "123";
    string hoge2 = "123a";
    string hoge3 = "a123";

    if (std::all_of(hoge.cbegin(), hoge.cend(), isdigit))
    {
        std::cout << "Intになれます" << std::endl;
    }
}

チェックできてる。ちなみに、#include <cctype>と、#include <algorithm>を外しても動いちゃんだけどなんでだろう。あと、using namespace std;というのは、本番開発では使わない方がいいらしい。衝突が起こるらしい。上記も衝突が起こった。std::all_ofというのの、stdというのは違うやつらしい。c++は難しい。

hoge.cpp
#include <iostream>
#include <cctype>
#include <algorithm>

bool check_int(std::string str)
{
    if (std::all_of(str.cbegin(), str.cend(), isdigit))
    {
        std::cout << stoi(str) << std::endl;
        return true;
    }
    std::cout << "not int" << std::endl;
    return false;
}

int main()
{
    using std::string;
    string hoge = "123";
    string hoge2 = "123a";
    string hoge3 = "a123";
    string hoge4 = "1234567890";

    check_int(hoge);
    check_int(hoge2);
    check_int(hoge3);
    check_int(hoge4);
}
hoge.cppの結果
123
not int
not int
1234567890

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
12