C language: write a program that reads the C source code from the standard input (terminal) and verifies that all curly braces appear correctly in pairs.
Write a program that reads the C source code from the standard input (terminal) and verifies that all curly braces appear correctly in pairs. For example, input: {}{}. The match is successful. Input: {}{}}, successful match input: {}}{, matched failed input: }}{{, matched failed input :{}}, failed match input: }{}{{, the match is not successful. Solution: Program:
# Include <stdio. h> # include <stdlib. h> int main () {int count = 0; char ch; printf ("enter a set of curly braces:"); while (ch = getchar ())! = EOF) // use Ctrl + Z to end {if (ch = '{') {count ++;} else if (ch = '}') {if (count = 0) {printf ("Mismatch failed \ n") ;}else {count -- ;}} if (count = 0) {printf ("matched \ n");} else {printf ("matched \ n ");} printf ("the excess '{' is % d \ n", count); system ("pause"); return 0 ;}
Result 1: Enter a set of curly braces: {{{}{}^ Z. If the matching fails, the excess '{' is three. Press any key to continue... result 2: enter a set of curly braces: {}}} ^ extra strings '{' that match successfully are 0. Press any key to continue...