简体   繁体   English

什么是scanf格式输入的cin analougus?

[英]What is the cin analougus of scanf formatted input?

With scanf there's, usually, a direct way to take formatted input: 通过scanf,通常可以直接获取格式化输入:

1) line with a real number higher than 0, and less than 1. Ending on 'x', eg: 0.32432523x 1)具有大于0且小于1的实数的行。在'x'上结束,例如: 0.32432523x

scanf("0.%[0-9]x", &number);

2) line represents an addition in the format :30+28=fifty-eight 2)line代表格式的加法:30 + 28 =五十八

scanf(":%d+%d=%99s", &number1, &number2, &total);

What is the cin solution, using only the standard library? 什么是cin解决方案,只使用标准库?

You can make a simple class to verify input. 您可以创建一个简单的类来验证输入。

struct confirm_input {
    char const *str;

    confirm_input( char const *in ) : str( in ) {}

    friend std::istream &operator >>
        ( std::istream &s, confirm_input const &o ) {

        for ( char const *p = o.str; * p; ++ p ) {
            if ( std::isspace( * p ) ) {
                std::istream::sentry k( s ); // discard whitespace
            } else if ( (c = s.get() ) != * p ) {
                s.setstate( std::ios::failbit ); // stop extracting
            }
        }
        return s;
     }
};

usage: 用法:

std::cin >> x >> confirm_input( " = " ) >> y;

Use the >> operator to read from cin. 使用>>运算符从cin读取。

  int number1, number2;
  std::string text;
  char plus, equals;
  std::cin >> number1 >> plus >> number2 >> equals >> text;
  if (!std::cin.fail() && plus == '+' && equals == '=' && !text.empty())
    std::cout << "matched";

It's not as good as scanf because you'd have to verify any literals that were in the scanf string yourself. 它不如scanf好,因为你必须自己验证scanf字符串中的任何文字。 Doing it with streams will almost certainly be a lot more lines of code than scanf. 使用流来完成它几乎肯定会比scanf更多的代码行。

I would use scanf. 我会用scanf。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM