본문 바로가기
CS+PS/data structure

[Stack] 스택 - 작은 따옴표 처리

by SolaBreeze 2023. 7. 3.

작은 따옴표 처리

입력 되는 문자열에 대한 아래 요건을 만족하는 프로그램을 만드시오.

  • 작은 따옴표 사이에 대한 문자열 무시
  • 작은 따옴표 처리 중 이스케이프 시퀀스 문자('\n','\\','\t' 등)에 대해서 정상적인 처리

INPUT

”EOF“를 입력 받을 때까지 문자열을 입력

OUTPUT

프로그램 검사 성공 여부에 따라 출력문은 아래와 같고 오류 시 오류가 생긴 문장의 라인,문자까지만 인정1) 성공 : OK, Line_count : (문장 수),  quotes_count : (작은 따옴표 짝 수)

2) 오류 : Error, Line_count : (문장 수), quotes_count : (작은 따옴표 짝 수)

- 아래 main 함수를 참조하여 checkMatching() 함수를 만드시오.

int main(){

std::string Str,temp;

while(true){

std::getline(std::cin,temp);

if(temp=="EOF")break;

Str.append(temp);

Str.append("\n");

std::cin.clear();    }

checkMatching(Str);

return 0;

}

Sample Input

' { { '

EOF

Sample Output

OK, Line_count : 1, quotes_count : 1

Sample Input

printf('left quotes_count\n');

printf('right quotes_count');

EOF

Sample Output

OK, Line_count : 2, quotes_count : 2

Sample Input

printf('escape_count'\n');

EOF

Sample Output

Error, Line_count : 1, quotes_count : 1

 

정답 : 

#include <iostream>
#include <string>
using namespace std;

void checkMatching(string &Str, int cnt){
    string ans;
    int qc = 0;
    int aa=0;
    bool quotes=false;
    int a;
    a = Str.length();
    for(int i=0; i<a; i++){
        if(Str[i]=='\''){
            // \'는 한개의 문자로 판별된다...(tlqkf!)
            // if(i-1>=0 && Str[i-1]=='\\'){ 
            //     continue;
            // }
            if (quotes){    //작은따옴표닫기
                qc++;
                quotes=false;
            }
            else {  //작은따옴표 열기
                quotes = true;
            }
        }
    }
    
    for(int i=0; i<a; i++){
        if (Str[i]=='\''){
            aa = 1;
        }
    }
    if(aa==1){
        if (quotes){
            ans = "Error";
        }
        else{
            ans="OK";
        }
    }
    else{
        ans="Error";
    }
    cout << ans <<", Line_count : "<<cnt<<", quotes_count : "<<qc<<endl;
}

int main(){
    string Str,temp;
    int cnt=0;
    while(true){
        getline(cin,temp);
        if(temp=="EOF")break;
        cnt++;
        cout << "\\'";
        Str.append(temp);
        // Str.append("\n");
        // cin.clear();
    }
    checkMatching(Str, cnt);
    return 0;
}