By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,134 Members | 1,195 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,134 IT Pros & Developers. It's quick & easy.

finding the sum combanation

P: 3
i have an input file with a set of numbers (number per line) , the numbers must include 0 followed by a line that specifies specifies the value of the sum.

example of input file:

5
1
4
3
7
9
0
10

the program should find all possible combination of the sum (10) from the numbers before the 0.

output file:

1 4 5

3 7

1 9

- i made the input file, i tried to save the numbers before the 0 in an array and save the number after the zero as the sum, the problem is that it takes all the numbers and even extra memory locations.

Code:

#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;


int main () {

int s,st[10] ;

ifstream in("exsum.in", ios::in);

int i=0;

while ("exsum.in") {
if (st[i]!=0){
in >> st[i] ;
cout << st[i] << endl;
i++;
}
}

in >> st[i+1];

s= st[i+1];

return 0;

}


- would appreciate any help ^^ , thanks
Dec 20 '06 #1
Share this Question
Share on Google+
3 Replies


Expert 100+
P: 1,510
you need to test for the 0 immediatly after reading a value from the file, e.g.
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <cstring>
  3. #include <fstream>
  4. using namespace std;
  5.  
  6. int main () {
  7. int s,st[10] ;
  8. ifstream in("exsum.in", ios::in);
  9.  
  10. int i=0;
  11.  
  12. while ("exsum.in") {
  13. in >> st[i] ;
  14. cout << st[i] << endl;
  15. if (st[i]==0) break;    // break if 0
  16. i++;
  17. }
  18.  
  19. in >> s;
  20. cout << " sum = " << s << endl;
  21.  
  22. return 0;
  23. }
  24.  
Dec 20 '06 #2

P: 3
thanks ^^. but now it gives me this as output, not the numbers

-858993460
-858993460
-858993460
-858993460
-858993460
-858993460
-858993460
-858993460
1245104
4496172
0
sum = -858993460
Dec 20 '06 #3

P: 3
oh nvm it worked now! thanks alot ^^
Dec 20 '06 #4

Post your reply

Sign in to post your reply or Sign up for a free account.