c++ - 使用 std::cin 忽略/跳过标记

标签 c++ scanf cin skip

使用 scanf 可以跳过匹配的标记,只需将 * 添加到模式中,如:

int first, second;
scanf("%d %*s %d", &first, &second);

是否有与 std::cin 等效的方法?类似的东西(当然,不使用额外的变量):

int first, second;
std::cin >> first >> `std::skip` >> second;

最佳答案

C++ 中的输入流做同样的事情并不是一项简单的任务。函数 scanf 获取所有预期格式:"%d %*s %d" 并且可以向前看以确定发生了什么。

另一方面,operator >>> 只是试图满足当前入口参数。


您有机会编写自己的 istream 操纵器来吃掉输入,直到达到一个数字。

试试这个我天真的代码:

template<typename C, typename T>
basic_istream<C, T>&
eat_until_digit(basic_istream<C, T>& in)
{
  const ctype<C>& ct = use_facet <ctype<C>> (in.getloc());

  basic_streambuf<C, T>* sb = in.rdbuf();

  int c = sb->sgetc();
  while (c != T::eof() && !ct.is(ctype_base::digit, c))
      c = sb->snextc();

  if (c == T::eof())
      in.setstate(ios_base::eofbit);

  return in;
}

int main()
{
    int first, second;

    cin >> first >> eat_until_digit >> second;

    cout << first << " : " << second << endl;
}

您可以扩展和改进上面的代码来实现您所需要的。

关于c++ - 使用 std::cin 忽略/跳过标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19068429/

相关文章:

c - 什么是 scanf ("%[^\n]%*c", &s);实际上呢?

c++ - 无字母循环

C++ c_str() 不返回完整的字符串

c++ - 如何在 Linux 上用 C++ 确定键盘按键被按下

c++ - Fortran 中的静态链接

c++ - 如何在 C++ 中的文件更改事件中获取文件名

C - scanf 被跳过(即使是 "%d")

c++ - 在 Windows 上构建 MLT 框架时出错

C、如何让程序在使用fork()时不跳过scanf()

c++ - 为什么这段代码会无限循环?