mardi 24 novembre 2015

Why the following code prints garbage values for input strings greater than 128 bytes?

This is a problem of codechef that I recently came across. The answer seems to be right for every test case where the value of input string is less than 128 bytes as it is passing a couple of test cases. For every value greater than 128 bytes it is printing out a large value which seems to be a garbage value.

std::string str;
std::cin>>str;
vector<pair<char,int>> v;
v.push_back(make_pair('C',0));
v.push_back(make_pair('H',0));
v.push_back(make_pair('E',0));
v.push_back(make_pair('F',0));
int i=0;
while(1)
{
    if(str[i]=='C')
        v['C'].second++;
    else if (str[i]=='H')
    {
        v['H'].second++;
        v['C'].second--;
    }
    else if (str[i]=='E')
    {
        v['E'].second++;
        v['C'].second--;
    }
    else if (str[i]=='F')
        v['F'].second++;
    else
        break;
    i++;

Even enclosing the same code within

/*reading the string values from a file and not console*/
std::string input;
std::ifstream infile("input.txt");
while(getline(infile,input)) 
{
    istringstream in(input);
    string str;
    in>>str;
    /* above code goes here */
}

generates the same result. I am not looking for any solution(s) or hint(s) to get to the right answer as I want to test the correctness of my algorithm. But I want to know why this happens as I am new to vector containers`.

-Regards.

Aucun commentaire:

Enregistrer un commentaire