【问题标题】:C++ cin vs. C sscanfC++ cin 与 C sscanf
【发布时间】:2011-10-27 22:23:20
【问题描述】:

所以我用 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++ 中做同样的事情?可能使用字符串流?

【问题讨论】:

    标签: c++ c stringstream cin scanf


    【解决方案1】:
    #include <string>
    #include <sstream>
    
    static void cmd_test(const char *s)
    {
        std::istringstream iss(s);
        std::string dummy;
        int d = maxdepth;
        iss >> dummy >> d;
    }
    

    【讨论】:

      【解决方案2】:

      你不能真正提取成匿名字符串,但你可以做一个假人并忽略它:

      #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);
      }
      

      【讨论】:

      • 也许参数从const char*更改为istringstream有点重?
      • @ChristianRau:谁知道...... OP 似乎正在处理有关字符串流的问题,也许他已经在某个地方有一个流。如果不是,您可以根据需要从const char* 构造一个。我添加了一条评论。
      • @KerrekSB 好点,实际上我也更喜欢流参数。但在这种情况下,一般的 istream 会更好。
      • @ChristianRau:好主意,我改了!
      • @KerrekSB 但是现在变化真的很大。您至少可以向他展示一个示例,当他只有一个 char* 或一个字符串时如何调用此函数(也可能将标头更改为 istream)。
      【解决方案3】:

      怎么样:

      #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;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-12-25
        • 2013-07-04
        • 1970-01-01
        • 1970-01-01
        • 2011-02-04
        • 2012-02-26
        • 1970-01-01
        • 2010-11-03
        • 2017-06-03
        相关资源
        最近更新 更多