Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // File I/O
- // Date : 23.11.19
- // Program will read from a file and add some value to it.
- // Then write it to file again.
- #include<iostream>
- #include<fstream>
- #include<vector>
- #include<sstream>
- using namespace std;
- void mainMenu();
- void ShowTheFile();
- vector<int> ReadFromFile();
- void WriteToFile();
- void AddValueToElementOfFile();
- void ShowTheFile(){
- // loop to show the array
- vector<int> inputArray = ReadFromFile();
- if(inputArray.size() == 0){
- cout << "File is empty or not exist.\n";
- }
- else{
- cout << "The file contains : " << endl;
- for(int i : inputArray){
- cout << i << ' ';
- }
- cout << endl << endl;
- }
- mainMenu();
- }
- vector<int> ReadFromFile(){
- ifstream readFile("file.txt");
- string input;
- vector<int> inputArray;
- // Loop to read all lines in file
- while(getline(readFile, input)){
- // separating each word from sentence
- stringstream s(input);
- string number;
- // Loop to read each word and convert to int value
- while(s >> number){
- int k = stoi(number, nullptr, 10);
- inputArray.push_back(k);
- }
- }
- readFile.close();
- return inputArray;
- }
- void WriteToFile(){
- ofstream writeFile("file.txt");
- cout << "Enter number of input: ";
- int n; cin >> n;
- for(int i = 0; i < n; i++){
- int k; cin >> k;
- writeFile << k << ' ';
- }
- writeFile.close();
- mainMenu();
- }
- void AddValueToElementOfFile(){
- vector<int> arrayInFile = ReadFromFile();
- int value;
- cout << "Enter the value to add with the elements of array: ";
- cin >> value;
- for(int i = 0; i < arrayInFile.size(); i++){
- arrayInFile[i] = arrayInFile[i] + value;
- }
- ofstream writeFile("file.txt");
- for(int i: arrayInFile){
- writeFile << i << ' ';
- }
- writeFile.close();
- mainMenu();
- }
- void mainMenu(){
- cout << "Read from the file: Press '1'" << endl
- << "Take input and write to file: Press '2'" << endl
- << "Take input value and add it to all values in file and the write it back : Press '3'" << endl
- << "Exit : Press '4'" << endl
- << endl
- << "Enter your choice: ";
- int choice; cin >> choice;
- switch(choice){
- case 1:
- ShowTheFile();
- break;
- case 2:
- WriteToFile();
- break;
- case 3:
- AddValueToElementOfFile();
- break;
- case 4:
- return;
- break;
- default:
- break;
- }
- }
- int main(){
- mainMenu();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement