gpt4 book ai didi

c++ - 使用 stod() 在小数点后转换带有字母的字符串时没有异常

转载 作者:行者123 更新时间:2023-11-30 01:36:24 25 4
gpt4 key购买 nike

#include<iostream>
#include<string>
using namespace std;

int main()
{
double var;
string word("20.njhggh");
var = stod(word);
cout << var << endl;
return 0;
}

输出是:20

stod 函数不会抛出输入 "20.njhggh" 的异常。它只是忽略小数点后的字母。对于上述情况,我如何抛出异常

最佳答案

How do I trow exception for the above case

根据文档,stod 有第二个参数:

double      stod( const std::string& str, std::size_t* pos = 0 );

If pos is not a null pointer, then a pointer ptr, internal to the conversion functions, will receive the address of the first unconverted character in str.c_str(), and the index of that character will be calculated and stored in *pos, giving the number of characters that were processed by the conversion.

因此,如果您想在某些字符串未用于转换时抛出异常,您可以将 *pos 与字符串的大小进行比较:

std::size_t pos;
var = stod(word, &pos);
if (pos < word.size())
throw some_exception();

关于c++ - 使用 stod() 在小数点后转换带有字母的字符串时没有异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52213117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com