What is the cin analougus of scanf formatted input?

前端 未结 2 1953
独厮守ぢ
独厮守ぢ 2020-12-03 05:32

With scanf there\'s, usually, a direct way to take formatted input:

1) line with a real number higher than 0, and less than 1. Ending on \'x\', e.g: 0.32432523x<

相关标签:
2条回答
  • 2020-12-03 06:09

    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;
    
    0 讨论(0)
  • 2020-12-03 06:16

    Use the >> operator to read from 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. Doing it with streams will almost certainly be a lot more lines of code than scanf.

    I would use scanf.

    0 讨论(0)
提交回复
热议问题