UVa 1596 - Bug Hunt(细节)

输入一段程序代码,要你找出bug,有两种bug,一是引用未赋值变量,二是下标越界。

主要考察的就是细节,思路并不难,找程序的bug,首先自己写的程序细节上不能出bug。

#include<iostream>
#include<string>
#include<sstream>
#include<map>
using namespace std;
string s0,s,s1,s2,left_value,right_value;
int bug;
map<string,unsigned int>a;
map<string,string>value;
string get_value(string x,string arr){
    unsigned int t=0;
    string y,z;
    if(x.find("[")==string::npos){
        stringstream ss(x);
        ss>>t;
        if(arr!=s0&&t>=a[arr]) bug=1;
        return x;
    }
    y=x.substr(0,x.find("["));
    z=x.substr(x.find("[")+1,x.find_last_of("]")-2);
    z=get_value(z,y);
    if(bug) return s0;
    x=y+"["+z+"]";
    if(!value.count(x)) bug=1;
    return value[x];
}
void get_arr(){
    string x,y;
    unsigned int z;
    x=s.substr(0,s.find("["));
    y=s.substr(s.find("[")+1,s.find_last_of("]")-2);
    y=get_value(y,s0);
    stringstream ss(y);
    ss>>z;
    a[x]=z;
    return;
}
int main(){
    int flag=0,cnt=1;
    a[s0]=0;
    string arr,indx;
    while(cin>>s){
        if(s!=".") flag=1;
        else if(!flag) break;
        else{
            if(!bug) cout<<"0"<<endl;
            a.clear();
            value.clear();
            left_value=right_value=s0;
            cnt=1;
            bug=flag=0;
            continue;
        }
        if(bug) continue;
        if(s.find("=")==string::npos) get_arr();
        else{
            s1=s.substr(0,s.find("="));
            s2=s.substr(s.find("=")+1);
            arr=s1.substr(0,s1.find("["));
            indx=s1.substr(s1.find("[")+1,s1.find_last_of("]")-2);
            indx=get_value(indx,arr);
            stringstream ss(indx);
            unsigned int t;
            ss>>t;
            if(t>=a[arr]) bug=1;
            left_value=arr+"["+indx+"]";
            right_value=get_value(s2,s0);
            if(bug){
                cout<<cnt<<endl;
                continue;
            }
            value[left_value]=right_value;
            left_value=right_value=s0;
        }
        cnt++;
    }
    return 0;
}


你可能感兴趣的:(UVa 1596 - Bug Hunt(细节))