4
4

1 回答 1

1

When using formatted input to read a std::string only the first word is read: after skipping leading whitespate a string is read until the first whitespace is encountered. As a result, the input ( ) should match but std::cin >> str would only read (. Thus, the input should probably look like this:

if (std::getline(std::cin, str)) {
    // algorithm for matching parenthesis and brackets goes here
}

Using std::getline() still makes an assumption about how the input is presented, namely that it is on one line. If the algorithm should process the entire input from std::cin I would use

str.assign(std::istreambuf_iterator<char>(std::cin),
           std::istreambuf_iterator<char>());

Although I think the algorithm is unnecessary complex (on stack storing the kind of parenthesis would suffice), I also think that it should work, i.e., the only problem I spotted is the way the input is obtained.

于 2013-09-15T18:30:25.410 回答