Saurabh Banore
Saurabh Banore

Reputation: 43

Runtime error in nested for loop C++

 for(i=0;i<np;i++){
    cin >> temp_str;
    pos = find(names.begin(), names.end(), temp_str) - names.begin();
    cin >> total >> ppl;
    giving.push_back(make_pair(pos, total));
    amt_getting = total / ppl;
    bal[pos] += total - (amt_getting * ppl);

    for(j = 0; j < np - 1; j++){   /**** Error due to this loop's condition******/
       cin >> temp_str;
       pos = find(names.begin(), names.end(), temp_str) - names.begin();
       bal[pos] += amt_getting;
    }

I am getting a runtime error in my program. This the code fragment where the RTE occurs. Whenever I change the condition j < np-1 to j < np the error gets fixed. What's the matter? I haven't even used any array inside the second for loop for segfault.

Upvotes: 0

Views: 683

Answers (1)

molbdnilo
molbdnilo

Reputation: 66459

You're not mentioning what kind of runtime error, so this is conjecture...

With np - 1, your code doesn't match the input; there's one non-integer more left in the stream.

This means that cin >> total >> ppl fails, ppl becomes zero, and total / ppl is a division by zero.

Upvotes: 1

Related Questions