Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...