I’m currently solving a programming problem to enhance my skills (I’m still a newbie) I’ve checked my solution line by line and I guess there isn’t any problem at all (Or is there?).
And here is my code:
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main(){
int nGroup;
ifstream in("gift1.in");
in >> nGroup;
string group[nGroup];
for (int i = 0; i < nGroup; i++){
in >> group[i];
}
int money[nGroup];
for (int i = 0; i < nGroup; i++) money[i] = 0;
string tempName;
int receivers,toGive,tempMoney;
while(!in.eof()){
in >> tempName;
// Give out money
for (int i = 0; i < nGroup; i++){ // Check for who gave
if (tempName.compare(group[i]) == 0){
in >> tempMoney >> receivers;
toGive = tempMoney / receivers;
money[i] -= (toGive * receivers);
}
}
// Receive money
for (int i = 1; i <= receivers; i++){
in >> tempName;
for (int j = 0; j < nGroup; j++){ // Check for who to receive
if (tempName.compare(group[j]) == 0){
money[j] += toGive;
}
}
}
}
// Write results to output file
ofstream fout("gist1.out");
for (int i = 0; i < nGroup; i++){
fout << group[i] << " " << money[i] << endl;
}
in.close();
fout.close();
system("PAUSE");
return 0;
}
Now, I tried debugging my code and I’m sure it’s working up to the “while(!in.eof()” part.
I intently inserted system(“PAUSE”); at the end part just to see if all have gone well, but the problem is that the program just blinks and done. It didn’t even created any output file at all.
I’ll be very grateful to anyone who can help a newbie like me into this. Thanks! 🙂
while (!in.eof())is almost always wrong. Where did you learn to do that?You also have no error handling around your stream extractions. None whatsoever. One of them is used to perform a integer division: what if the division happens with
0?Get yourself into the habit of using a debugger to find out what’s going on. Stack Overflow is not a debugger.