开发者

hash_map crashing in c++ stl

i am relatively experienced in Java coding but am new to C++. I have written the following C++ code as solution to the USACO training problem which I have reproduced at this url

This code looks fine to me. However it crashes on the sample test case given. On isolating the error, I found that if the second for loop is not run for the last iteration (I mean like in the sample test case, n = 5, so I run the loop only till i = 3 instead of i = 4), then it doesn't crash (and produces the expected output). Maybe the error is somewhere else, I can't detect it.

Any ideas are welcome. Thanks in advance. Please excuse me for the slightly unwieldy formatting of the code (this is my first forum post). The files included are stdlib.h, stdio.h and hash_map.h `

#include <stdlib.h>
#include <stdio.h>
#include <hash_map.h>

struct eqstr
{
  bool operator()(const char* s1, const char* s2) const
  {
    return strcmp(s1, s2) == 0;
  }
};


int main(int argc, char** argv) {

    FILE *fin = fopen("gift1.in", "r");
    FILE *fout = fopen("gift1.out", "w");


    hash_map<const char*, int, hash<const char*>, eqstr> table;

    int n;
    fscanf(fin,"%d",&n);
    char name[15];
    char people[10][15];

    for(int i = 0; i < n; i++){
        fscanf(fin,"%s",name);
        strcpy(people[i],name);
        table[people[i]] = 0;
    }//ifor

    for(int i = 0; i < n; i++){
        fscanf(fin,"%s",name);
        int money;
        fscanf(fin,"%d",&money);
        int friends;
        fscanf(fin,"%d",&friends);
        char fname[15];
        int amt = money/friends;
        for(int j = 0; j < friends; j++){
            fscanf(fin,"%s",fname);
            table[fname] = table[fname] + amt;
        }//jfor
        table[name] = table[name] - friends*amt;
    }//ifor

    for(int i = 0; i < n; i++)
        fprintf(f开发者_运维知识库out,"%s %d\n",people[i],table[people[i]]);

    return (EXIT_SUCCESS);
}

`


The reason it is crashing is that vick is giving 0 friends money which causes a divide by zero exception from the following line of code: int amt = money/friends;

You should put in some special logic to handle the case when the person has 0 friends so gives $0 away.

As was stated in the other comments, you should use some stl classes (string,iostream, etc) to help clean up the code.

Edit: Added the input data so the question and answer would make a little more sense

5
dave
laura
owen
vick
amr
dave
200 3
laura
owen
vick
owen
500 1
dave
amr
150 2
vick
owen
laura
0 2
amr
vick
vick
0 0


I would suggest using GDB to find these errors. These occured to me also.

Compile with -g flag, then use gdb a.out(executable). Now type run to run the program. Once the program crashes, you can use backtrace to identify the exact line where its crashing and the variable values at that point.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜