C++将字符串转换为整数;获得怪异的输出
C++ Converting String to Integer; Getting Weird outputs?
我有以下代码:
{
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
相关文章:
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何从void函数输出字符串
- 输出字符串数组
- 如何输出字符串第二个单词的第一个字母?
- 多线程环境中的输出字符串流出现问题
- 输出字符串到cmd显示的右显示,但未被认为是命令
- 读取文本文件并输出字符串
- 输出字符串使用 C++ 覆盖 Linux 终端上的最后一个字符串
- 如何在C++中输出字符串的向量
- 无法从类模板输出字符串
- FWRITE 输出字符串不正确
- Qt单元测试输出字符串长度截止
- 无法显示输出字符串
- 如果条目大于90,则输出字符串的布尔函数
- C++不带 'n' 或 endl 的输出字符串将在字符串末尾输出'#'
- 在C++中输出字符串和 strncpy 时遇到问题
- 获取c#输出字符串参数值为c++ BSTR*
- C++初学者,开关不输出字符串的第一个字符
- 输出字符串/字符错误(c++)
- Getline()省略输出字符串的第一个字母