C++ cin vs. C sscanf

C++ cin vs. C sscanf

本文关键字:sscanf vs cin C++      更新时间:2023-10-16

所以我用C写的,所以sscanf扫描s,然后丢弃它,然后扫描d并存储它。因此,如果输入为"Hello 007",则扫描Hello但丢弃,007存储在d中。

static void cmd_test(const char *s)
{
    int d = maxdepth;
    sscanf(s, "%*s%d", &d);
}

所以,我的问题是我怎么能做同样的事情,但在c++ ?可能使用stringstream?

#include <string>
#include <sstream>
static void cmd_test(const char *s)
{
    std::istringstream iss(s);
    std::string dummy;
    int d = maxdepth;
    iss >> dummy >> d;
}

您不能真正提取到匿名字符串中,但您可以创建一个dummy并忽略它:

#include <string>
#include <istream>
// #include <sstream> // see below
void cmd_test(std::istream & iss) // any std::istream will do!
{
  // alternatively, pass a `const char * str` as the argument,
  // change the above header inclusion, and declare:
  // std::istringstream iss(str);
  int d;
  std::string s;
  if (!(iss >> s >> d)) { /* maybe handle error */ }
  // now `d` holds your value if the above succeeded
}

注意,提取可能会失败,因为我输入了条件。这取决于你在出现错误时怎么做;c++要做的事情是抛出一个异常(尽管如果你的实际函数已经传达了错误,你可能只需要return一个错误)。

使用例子:

#include <iostream>
#include <fstream>
int main()
{
  cmd_test(std::cin);
  std::ifstream infile("myfile.txt");
  cmd_test(infile);
  std::string s = get_string_from_user();
  std::istringstream iss(s);
  cmd_test(iss);
}

怎么样:

#include <string>
#include <sstream>
static void cmd_test(const std::string &s)
{
    int d = maxdepth;
    std::string dont_care;
    std::istringstream in(s);
    in >> dont_care >> d;
}