2014-10-21 64 views
0

我有以下代码:C++将字符串转换为整数;获得奇怪的输出?

{ 
      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

你试图解析文本语法?你可能应该[用XY表示你的问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 – sehe 2014-10-21 23:31:07

回答

1

由于您使用升压:

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