boost lexical_cast 抛出异常
我正在使用 c++ 的 boost 库,并且函数 lexical_cast 的行为非常奇怪。如果我执行 lexical_cast("0.07513994") 它工作正常,但如果我使用需要转换的变量,它会抛出 bad_lexical_cast 异常。这是代码:
string word;
istringstream iss(line);
do
{
string word;
iss >> word;
double x;
x = lexical_cast<double>(word);
cout << x << endl;
} while (iss);
我在这里做错了什么?我感谢任何帮助,谢谢
I'm using boost libs for c++ and the function lexical_cast behaves really weird. If I do lexical_cast("0.07513994") it works fine, but if I use my variable which I need to convert, it throws the bad_lexical_cast exception. Here is the code:
string word;
istringstream iss(line);
do
{
string word;
iss >> word;
double x;
x = lexical_cast<double>(word);
cout << x << endl;
} while (iss);
What am I doing wrong here? I appreciate any help, thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的问题可能是循环的处理次数比您预期的多一次。
最后一次循环时,读取字失败,在 iss 中设置失败位,这就是 while(iss) 正在检查的内容。要修复它,您需要执行类似的操作。
Your problem is probably that the loop is processed one more time than you expect.
The last time through the loop, the read to word fails, setting the fail bit in iss, which is what while(iss) is checking. To fix it you need to do something like this.
与 atof() 等函数在看到无效字符后立即停止解析不同,lexical_cast 要求输入字符串中的每个字符都有效。即任何前导或尾随空格都会导致它抛出异常。
您想查看它正在获取什么样的输入并相应地进行调整。您还应该捕获 bad_lexical_cast 以防万一它确实获得完全垃圾的输入。
一种可能的解决方案是使用 boos.regex 或 boost.xpressive 提取有效的子字符串并将结果传递给 lexical_cast。
Unlike functions such as atof() which stop parsing as soon as they see an invalid character, lexical_cast requires that every character in the input string be valid. i.e. any leading or trailing spaces will cause it to throw an exception.
You want to see what kind of input it is getting and trim it accordingly. You should also catch bad_lexical_cast just in case it does get input which is completely garbage.
One possible solution is to use boos.regex or boost.xpressive to extract a valid sub-string and pass the result to lexical_cast.
问题可能是当没有剩余数据时您发送一个空字符串。
您应该更改正在使用的循环。
使用 while {} 循环(而不是“do while”循环)。这允许您从流中读取数据并在单个易于阅读的语句中对其进行测试。注意 iss >> 的结果词就是流。当在此布尔上下文中使用时,将对其进行测试以查看状态是否良好以及其值是否转换为可由 while 条件使用的值。因此,如果运算符>>如果提交正确工作,则永远不会进入循环。
但实际上,在这种情况下你甚至不需要词法转换(除非你想测试非数字但有例外)。标准流运算符会将输入转换为双精度型。
The problem is probably that you are sending an empty string when there is no data left.
You should change the loop you are using.
Use the while {} loop (not the 'do while' loop). This allows you to read from the stream and test it in a single easy to read statement. Note the result of iss >> word is the stream. When used in this boolean context it is tested to see if the state is good and its value converted into something that can be used by the while condition. Thus if the operator >> filed to work correctly then the loop is never entered.
But really you don't even need the lexical cast in this situation (unless you want to test for non numbers with an exception). The standard stream operator will convert the input into a double.