1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
#include <iostream> #include <fstream> #include <vector> using namespace std; // Function to read integers from a file vector<int> readIntegersFromFile(const string& filename) { ifstream file(filename); if (!file) { cerr << "Error opening file for reading: " << filename << endl; exit(1); } vector<int> numbers; int number; while (file >> number) { numbers.push_back(number); } file.close(); return numbers; } // Function to write the sum to a file void writeSumToFile(const string& filename, int sum) { ofstream file(filename); if (!file) { cerr << "Error opening file for writing: " << filename << endl; exit(1); } file << "Sum of integers: " << sum << endl; file.close(); } int main() { string inputFilename, outputFilename; cout << "Enter the input file name: "; cin >> inputFilename; cout << "Enter the output file name: "; cin >> outputFilename; // Read integers from the input file vector<int> numbers = readIntegersFromFile(inputFilename); // Calculate the sum of integers int sum = 0; for (int number : numbers) { sum += number; } // Write the sum to the output file writeSumToFile(outputFilename, sum); cout << "Sum calculation complete. Check the output file: " << outputFilename << endl; return 0; } |
Explanation:
- Reading from a File (
readIntegersFromFile
):- Opens a file for reading using an
ifstream
. - Checks if the file was successfully opened.
- Reads integers from the file and stores them in a
vector<int>
. - Closes the file and returns the vector of integers.
- Opens a file for reading using an
- Writing to a File (
writeSumToFile
Advertisement- Opens a file for writing using an
ofstream
. - Checks if the file was successfully opened.
- Writes the sum of integers to the file.
- Closes the file.
- Opens a file for writing using an
- Main Function (
main
):- Prompts the user for the input and output filenames.
- Calls
readIntegersFromFile
to read integers from the input file. - Calculates the sum of the integers.
- Calls
writeSumToFile
to write the sum to the output file. - Prints a message indicating completion and the location of the output file.
Possible Enhancements:
- Error Handling: Add more robust error handling to manage different file-related issues.
- Data Validation: Implement checks to validate the data read from the file (e.g., ensure it contains only integers).
- Flexible Data Processing: Extend the program to handle different types of data and perform more complex processing.
- Command-Line Arguments: Modify the program to accept filenames as command-line arguments for more flexible usage.
Advertisement