简体   繁体   中英

how to read chars from istream in C++?

I am trying to validate the istream using several if statements in the following syntax:

bool foo(std::istream& input) {
    char b1;
    char b2;
    int i;

    input >> b1;

    if (b1 == '(') {
        input >> i;
        input >> b2;

        if (b2 == ')') {
            return true;
        }
    }

    return false;
}

The input should be in the format: (a) .

The function returns false for every istream.

You could use a rather simple if -statement to validate the input.

It will work as follows. First, you will try to read the brackets and the values from the stream. The stream has a state and will indicate, if the operation works or not.

You will find a real good overview here

There are several functions with which you can check the result of an IO operation. We will use the bool operator and take advantage of the fact that most IO operations retrun a reference to the stream on which they are called.

So, for example std::cin >> a >> b >> c wil return a reference to std::cin . And if you put the above expression in an if statement, then this will expect a boolean expression. Hence the bool operator of the stream will be called.

Next, we take advantage of C++ boolean shortcut evaluation and come up with the final solution.

Please see:

#include <iostream>
#include <fstream>
#include <sstream>
using namespace std::string_literals;

// Testdata
std::istringstream testOK{ "( 123 )" };
std::istringstream testNOK{ "( 456 " };

int main() {

    int value{}; 
    char bOpen{}; 
    char bClose{};
    
    // Read and validate
    if ((testOK >> bOpen >> value >> bClose) and (bOpen == '(') and (bClose == ')'))
        std::cout << value;
    else
        std::cout << "\n*** Error: Invalid Input1\n";

    // Read and validate
    if ((testNOK >> bOpen >> value >> bClose) and (bOpen == '(') and (bClose == ')'))
        std::cout << value;
    else
        std::cout << "\n*** Error: Invalid Input2\n";
}

We first check, if the IO operation worked successful. If, and only if, then we will evaluate the brackets.

BTW. It is recommeded, to always check the result of IO operations (maybe sometimes except if inserting something into std::cout )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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