C++将字符串转换为整数;获得怪异的输出

C++ Converting String to Integer; Getting Weird outputs?

本文关键字:输出 字符串 转换 整数 C++      更新时间:2023-10-16

我有以下代码:

    {
            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"吗?

由于您使用的是boost:

在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 matchedn";
    }
}

打印:

Matched: 1234

如果你想知道为什么要做这样的事情,而不是手动处理所有的字符串:LiveOnColiru

#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 errorn";
    }
}

打印

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