Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

c++ - How to check std::string if its indeed an integer?

The following code converts an std::string to int and the problem lies with the fact that it cannot discern from a true integer or just a random string. Is there a systematic method for dealing with such a problem?

#include <cstring>
#include <iostream>
#include <sstream>

int main()
{
    std::string str =  "H";

    int int_value;
    std::istringstream ss(str);
    ss >> int_value;

    std::cout<<int_value<<std::endl;

    return 0;
}

EDIT: This is the solution that I liked because it is very minimal and elegant! It doesn't work for negative numbers but I only needed positive ones anyways.

#include <cstring>
#include <iostream>
#include <sstream>

int main()
{
    std::string str =  "2147483647";

    int int_value;
    std::istringstream ss(str);

    if (ss >> int_value)
        std::cout << "Hooray!" << std::endl;

    std::cout<<int_value<<std::endl;


    str =  "-2147483648";
    std::istringstream negative_ss(str);

    if (ss >> int_value)
        std::cout << "Hooray!" << std::endl;

    std::cout<<int_value<<std::endl;

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may try to use Boost lexical_cast, it will throw an exception if the cast failed.

int number;
try
{
     number = boost::lexical_cast<int>(str);
}
catch(boost::bad_lexical_cast& e)
{
    std::cout << str << "isn't an integer number" << std::endl;
}

EDIT Accorinding to @chris, You may also try to use std::stoi since C++11. It will throw std::invalid_argument exception if no conversion could be performed. You may find more information here: std::stoi


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...