27

我有一个 sscanf 解决的问题(从字符串中提取内容)。不过我不喜欢 sscanf ,因为它不是类型安全的,而且又旧又可怕。我想聪明一点,使用 C++ 标准库的一些更现代的部分。我应该改用什么?

4

5 回答 5

40

尝试std::stringstream

#include <sstream>

...

std::stringstream s("123 456 789");
int a, b, c;
s >> a >> b >> c;
于 2009-06-23T15:22:09.587 回答
7

对于大多数工作,标准流可以完美地完成工作,

std::string data = "AraK 22 4.0";
std::stringstream convertor(data);
std::string name;
int age;
double gpa;

convertor >> name >> age >> gpa;

if(convertor.fail() == true)
{
    // if the data string is not well-formatted do what ever you want here
}

如果您需要更强大的工具来进行更复杂的解析,那么您可以考虑使用 Regex 甚至 Boost 的 Spirit。

于 2009-06-23T23:03:11.580 回答
2

如果包含sstream,您将可以访问为字符串提供流的 stringstream 类,这正是您所需要的。Roguewave 有一些很好的例子来说明如何使用它。

于 2009-06-23T15:23:11.147 回答
0

如果你真的不想使用流(因为可读性很好),你可以使用 StringPrintf。

你可以在 Folly 中找到它的实现:

https://github.com/facebook/folly/blob/master/folly/String.h#L165

于 2013-08-07T19:12:44.187 回答
-1

fgets 或 strtol

于 2009-06-23T15:16:01.457 回答