fork download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <vector>
  4.  
  5. int main(void)
  6. {
  7. auto& datafile = std::cin;
  8.  
  9. if (!datafile) {
  10. std::cerr << "Could not open \'foo.txt\', make sure it is in the correct directory." << std::endl;
  11. exit(-1);
  12. }
  13.  
  14. int num_entries;
  15. // this tests whether the number was gotten successfully
  16. if (!(datafile >> num_entries)) {
  17. std::cerr << "The first item in the file must be the number of entries." << std::endl;
  18. exit(-1);
  19. }
  20.  
  21. // here we range check the input... never trust that information from the user is reasonable!
  22. if (num_entries < 0) {
  23. std::cerr << "Number of entries cannot be negative." << std::endl;
  24. exit(-2);
  25. }
  26.  
  27. // here we allocate an array of the requested size.
  28. // vector will take care of freeing the memory when we're done with it (the vector goes out of scope)
  29. std::vector<int> ints(num_entries);
  30. int sum = 0;
  31. for( int i = 0; i < num_entries; ++i ) {
  32. // again, we'll check if there was any problem reading the numbers
  33. if (!(datafile >> ints[i])) {
  34. std::cerr << "Error reading entry #" << i << std::endl;
  35. exit(-3);
  36. }
  37. sum += ints[i];
  38. }
  39.  
  40. std::cout << "Read " << num_entries << " numbers having a sum of " << sum << std::endl;
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0s 3432KB
stdin
3
3 4 2
stdout
Read 3 numbers having a sum of 9