簡體   English   中英

C ++ cin vs. C sscanf

[英]C++ cin vs. C sscanf

所以我在C中寫了這個,所以sscanf掃描s然后丟棄它,然后掃描並存儲它。 因此,如果輸入為“Hello 007”,則掃描Hello但丟棄,並將d7存儲在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;
}

你不能真正提取成一個匿名字符串,但你可以做一個虛擬並忽略它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM