gpt4 book ai didi

c++ - C++ (gcc) 中是否有等效的 TryParse?

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:47 33 4
gpt4 key购买 nike

在 C++(gcc) 中是否有等效的 TryParse?

我想解析一个可能包含 (+31321) 的字符串并将其存储很长时间。我知道电话号码存储为字符串和匹配的字符串,但出于我的需要,我想将它们存储很长时间,有时它们可​​能包含加号 (+)。什么会在 C++ 中解析它?

最佳答案

strtoul() 及其系列的问题是没有真正的方法来测试失败。
如果解析失败,则返回 0 而不设置 errno(仅在溢出时设置)。

提高词汇量

#include <boost/lexical_cast.hpp>


int main()
{
try
{
long x = boost::lexical_cast<long>("+1234");
std::cout << "X is " << x << "\n";
}
catch(...)
{
std::cout << "Failed\n";
}
}

使用流来实现

int main()
{
try
{
std::stringstream stream("+1234");
long x;
char test;

if ((!(stream >> x)) || (stream >> test))
{
// You should test that the stream into x worked.
// You should also test that there is nothing left in the stream
// Above: if (stream >> test) is good then there was content left after the long
// This is an indication that the value you were parsing is not a number.
throw std::runtime_error("Failed");
}
std::cout << "X is " << x << "\n";
}
catch(...)
{
std::cout << "Failed\n";
}
}

使用扫描:

int main()
{
try
{
char integer[] = "+1234";
long x;
int len;

if (sscanf(integer, "%ld%n", &x, &len) != 1 || (len != strlen(integer)))
{
// Check the scanf worked.
// Also check the scanf() read everything from the string.
// If there was anything left it indicates a failure.
throw std::runtime_error("Failed");
}
std::cout << "X is " << x << "\n";
}
catch(...)
{
std::cout << "Failed\n";
}
}

关于c++ - C++ (gcc) 中是否有等效的 TryParse?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8631327/

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