【问题标题】:C++ Converting String to Integer; Getting Weird outputs?C++ 将字符串转换为整数;得到奇怪的输出?
【发布时间】:2014-10-21 23:09:53
【问题描述】:

我有以下代码:

    {
            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”?

【问题讨论】:

标签: c++ string boost integer


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2014-08-28
    相关资源
    最近更新 更多