代码之家  ›  专栏  ›  技术社区  ›  Ben Hymers

我应该用什么来代替sscanf?

  •  26
  • Ben Hymers  · 技术社区  · 17 年前

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

    5 回复  |  直到 17 年前
        1
  •  40
  •   Fred Larson    8 年前

    尝试 std::stringstream

    #include <sstream>
    
    ...
    
    std::stringstream s("123 456 789");
    int a, b, c;
    s >> a >> b >> c;
    
        2
  •  7
  •   Khaled Alshaya    17 年前

    对于大多数工作,标准流都能完美地完成这项工作,

    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
    }
    

    如果需要更强大的工具进行更复杂的解析,那么可以从升压中考虑正则表达式甚至精神。

        3
  •  2
  •   Sebastian Mach    14 年前

    sstream 您可以访问为字符串提供流的stringstream类,这正是您所需要的。Roguewave有一些好处 examples on how to use it.

        4
  •  0
  •   iampat    13 年前

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

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

        5
  •  -1
  •   joe    17 年前