C ++将String转换为Integer;获得奇怪的输出?

时间:2014-10-21 23:09:53

标签: c++ string boost integer

我有以下代码:

    {
            line.erase(remove_if(line.begin(), line.end(), ::isspace), line.end()); //removes whitespace        
            vector<string> strs;
            boost::split(strs, line, boost::is_any_of("="));
            strs[1].erase(std::remove(strs[1].begin(), strs[1].end(), ';'), strs[1].end()); //remove semicolons 
    if(strs[0] == "NbProducts") { NbProducts = atoi(strs[1].c_str());
            istringstream buffer(strs[1]);
            buffer >> NbProducts; 
    }

但每当我尝试输出NbProducts时,我都会得到一个非常随机的数字。顺便说一句,输入来自正在阅读的文本文件:单行阅读:

"NbProducts = 1234;"

没有引号。

我知道代码现在有点草率。但是,任何人都可以立即看到为什么我可能会在“NbProducts”中获得奇怪的整数吗?

1 个答案:

答案 0 :(得分:1)

因为你正在使用boost:

<强> Live On Coliru

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_match.hpp>
#include <sstream>

namespace qi = boost::spirit::qi;

int main()
{
    std::istringstream buffer("NbProducts = 1234;");

    int NbProducts;
    if (buffer >> qi::phrase_match(
            qi::lit("NbProducts") >> "=" >> qi::int_ >> ";", 
            qi::space, NbProducts))
    {
        std::cout << "Matched: " << NbProducts << "\n";
    } else
    {
        std::cout << "Not matched\n";
    }
}

打印:

Matched: 1234

如果您想知道为什么要做这样的事情,而不是手动执行所有字符串处理: Live On Coliru

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_match.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <sstream>
#include <map>

namespace qi = boost::spirit::qi;
typedef qi::real_parser<double, qi::strict_real_policies<double> > sdouble_;
typedef boost::variant<int, double, std::string> value;

int main()
{
    std::istringstream buffer("NbProducts = 1234; SomethingElse = 789.42; Last = 'Some text';");

    std::map<std::string, value> config;

    if (buffer >> std::noskipws >> qi::phrase_match(
            *(+~qi::char_("=") >> '=' >> (qi::lexeme["'" >> *~qi::char_("'") >> "'"] | sdouble_() | qi::int_) >> ';'),
            qi::space, config))
    {
        for(auto& entry : config)
            std::cout << "Key '" << entry.first << "', value: " << entry.second << "\n";
    } else
    {
        std::cout << "Parse error\n";
    }
}

打印

Key 'Last', value: Some text
Key 'NbProducts', value: 1234
Key 'SomethingElse', value: 789.42