1. Write a program that asks the user to input one number at a time and then the program should add the number to previous sum. If the user enters -1, then no more addition is to be done. All these numbers along with the sum value are to be stored in the file.
Once this is done, user will enter value of n, the program should be able to display which was the nth number entered and what was the sum at that time?
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <utility>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
int num,sum = 0;
cout <<"Input numbers\n";
while (true){
cin >> num;
sum += num;
if (num == -1){
break;
}
else{
ofstream myfile;
myfile.open("file.txt", ios::app);
myfile <<num <<" "<<sum <<endl;
myfile.close();
}
}
int n;
cout << "\nInput nth number: ";
cin >> n;
string line;
ifstream myfile ("file.txt");
if (myfile.is_open())
{
int counter = 0;
while ( getline (myfile,line) )
{
if (n == 1 && counter == 0){
cout <<line;
break;
}
else if (n - 1 == counter){
istringstream this_line(line);
istream_iterator<int> begin(this_line), end;
vector<int> values(begin, end);
cout << "Nth number: "<<values[0]<<endl;
cout << "Sum: "<< values[1]<<endl;
break;
}
else{
counter++;
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
Comments
Leave a comment