I need to write a program PPP2 Chapter 5 Exercise 8 for which I have to ask for an input n from the user and then get numbers into a vector for as long as the user hasn't pressed '|' (meaning that the number of numbers entered can be more than n). Then I have to sum the n numbers from the vector and print the result. I've tried doing what I could, but I'm trouble figuring out how to sum just the first n numbers.
// chapter5ex8.cpp : Defines the entry point for the console application.
// Osman Zakir
// 1 / 1 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 5 Exerice 8
// Program to ask user for a number n and then have them enter a sequence of
// numbers, stopping with '|'. The program will then print the sum of the first
// n numbers. The program print an error message if the user enters
// less than n numbers.
#include "../../std_lib_facilities.h"
int get_n();
int main()
{
cout << "Please enter the numbers of values you want to sum: ";
int n = get_n();
int number = 0;
vector<int> numbers;
bool stop = false;
char terminate = '|';
char input = ' ';
int sum = 0;
cout << "Please enter some integers (press '|' to stop): ";
while (!stop)
{
cin >> number;
cin.ignore();
numbers.push_back(number);
if (numbers.size() == n + 1)
{
for (unsigned i = 0; i < numbers.size(); ++i)
{
sum += numbers[i];
}
}
cin.get(input);
if (input == terminate)
{
stop = true;
break;
}
}
try
{
if (numbers.size() < n)
{
error("value of n is too high!");
}
}
catch (const runtime_error &e)
{
cerr << "error: " << e.what() << '\n';
do
{
cout << "Enter a value of n not less than " << numbers.size() << '\n';
cin >> n;
cin.ignore();
}
while (n > numbers.size());
}
cout << "The sum of the first " << n << " values you entered is " << sum << '\n';
keep_window_open();
}
int get_n()
{
int n = 0;
cin >> n;
cin.ignore();
return n;
}
Even though the cout say "enter more input or | to terminate:", if the user enter anything that is not a number, then the cin will be in a bad state and the while loop will end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <vector>
#include <numeric>
usingnamespace std;
int main()
{
vector<int> nums;
int n;
cout << "enter input: ";
while (cin >> n)
{
nums.push_back(n);
cout << "enter more input or | to terminate: ";
}
cout << accumulate(nums.cbegin(), nums.cend(), 0) << endl;
return 0;
}
#include <iostream>
#include <vector>
usingnamespace std;
int main()
{
cout << "Please enter the numbers of values you want to sum : ";
size_t number_count = 0;
cin >> number_count;
vector<int> numbers;
for (int num; cin >> num;)
{
numbers.push_back(num);
}
if (numbers.size() > number_count)
{
cout << "You entered too many numbers.";
system("pause");
return -1;
}
elseif (numbers.size() < number_count)
{
cout << "You entered not enough numbers.";
system("pause");
return -1;
}
int sum = 0;
for (int n : numbers)
{
sum += n;
}
cout << "The sum is: " << sum << "\n\n";
system("pause");
return EXIT_SUCCESS;
}
I know, but if I did it like that here, input would be terminated whenever cin goes into a bad state, which would happen whenever anything that isn't a number is entered. It wouldn't just be limited to '|'.
That would sum all of the numbers in the vector. I want it to only sum the first n numbers.
A sample run of the program is given like this in the book:
“Please enter the number of values you want to sum:”
3
“Please enter some integers (press ' | ' to stop):”
12 23 13 24 15 |
“The sum of the first 3 numbers ( 12 23 13 ) is 48 .”
Right now, with that same input, the result I get from my program is 22.
#include <iostream>
#include <vector>
#include <numeric>
usingnamespace std;
bool RestoreStream(istream& cin)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "clearing stream" << endl;
returntrue;
}
int main()
{
int valueToSum{};
//////Ask number of inputs//////
do
{
cout << "Please enter the number of values you want to sum:";
//if the user mess up with the input and the cin fail, then the while
//evaluate to true and && evaluate the right side restoring the stream
//otherwise if input is good, we leave this loop
} while (!(cin >> valueToSum).ignore() && RestoreStream(cin));
////Get numbers/////////////////
vector<int> nums;
int temp{};
if (valueToSum > 0)
{
cout << "Please enter some integers(press ' | ' to stop) :";
while (!(cin.peek() == '|'))
{
(cin >> temp).ignore();
if (cin.fail())
{
RestoreStream(cin);
continue;
}
nums.push_back(temp);
}
}
///Sum if enough numbers where provided////
if (nums.size() >= valueToSum)
{
cout << "The sum of the first " << valueToSum <<
" numbers is "<< accumulate(nums.cbegin(), (nums.cbegin() + valueToSum), 0) << endl;
}
else
{
cout << "not enough inputs." << endl;
}
return 0;
}
Edit: ok, I've removed 2 bugs and tested, it works and give the correct resoult.
@DragonOsman
cbegin() returns a const interator while begin() return a non const, be using cbegin when we do not intend to modify the value is just good practice.
The numeric header is needed to call accumulate(), which will do the running sum from the vector begin() up to but not including the iterator begin()+N.
So if you had 3 as number of input as in the example, accumulate will return you the sum from vector.begin() up to but not including vector.begin()+N which means the sum of vector[0] + vector[1] + vector[2]
// chapter5ex8.cpp : Defines the entry point for the console application.
// Osman Zakir
// 1 / 1 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 5 Exerice 8
// Program to ask user for a number n and then have them enter a sequence of
// numbers, stopping with '|'. The program will then print the sum of the first
// n numbers. The program print an error message if the user enters
// less than n numbers.
#include "../../std_lib_facilities.h"
#include <numeric>
int get_n();
bool clear_stream(istream& cin);
int main()
{
cout << "Please enter the numbers of values you want to sum: ";
int n = get_n();
int number = 0;
vector<int> numbers;
if (n > 0)
{
cout << "Please enter some integers (press '|' to stop): ";
while (!(cin.peek() != '|'))
{
cin >> number;
cin.ignore();
numbers.push_back(number);
if (cin.fail())
{
clear_stream(cin);
continue;
}
}
try
{
if (numbers.size() < n)
{
error("too few numbers entered!");
}
}
catch (const runtime_error &e)
{
cerr << "error: " << e.what() << '\n';
do
{
cout << "Please enter a value for n not less than the number values entered: ";
cin >> n;
cin.ignore();
}
while (n < numbers.size());
}
int sum = accumulate(numbers.cbegin(), (numbers.cbegin() + n), 0);
cout << "The sum of the first " << n << " numbers is " << sum << '\n';
}
keep_window_open();
}
int get_n()
{
int n = 0;
cin >> n;
cin.ignore();
return n;
}
bool clear_stream(istream& cin)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
returntrue;
}
I get a Debug Assertion Failure error after I enter my numbers for the vector, and the error message saying that I entered too few numbers is printed to the console window.
Well, you are using your variable "n" both to store the number of input we want to sum in the end (3, according to the example from the book), and to store the following several inputs from the user in
1 2
cout << "Please enter a value for n not less than the number values entered: ";
cin >> n;
So if the last user input is 55, in the call to
int sum = accumulate(numbers.cbegin(), (numbers.cbegin() + n), 0);
you are trying to accumulate up to vector[54] which is madness xD
And on top of it, this while (!(cin.peek() != '|'))
if you enter a number, then (cin.peek() != '|') will evaluate true, the !() will reverse it to false, so you actually never enter the while and your number vector is always empty.
#include <iostream>
#include <vector>
usingnamespace std;
int main()
{
cout << "Please enter the numbers of values you want to sum : ";
size_t number_count = 0;
cin >> number_count;
vector<int> numbers;
for (int num; cin >> num;)
{
numbers.push_back(num);
}
if (numbers.size() < number_count)
{
cout << "You entered not enough numbers.";
system("pause");
return -1;
}
int sum = 0;
for (size_t i = 0; i < number_count; ++i)
{
sum += numbers[i];
}
cout << "The sum is: " << sum << "\n\n";
system("pause");
return EXIT_SUCCESS;
}
OUTPUT:
Please enter the numbers of values you want to sum : 3
1 2 3 4 5 |
The sum is: 6
@Marcus: Yeah, I guess I shouldn't have put != in there. It should've been == because of the ! outside the parentheses.
As for using n to store an input again, that's for handling a case where the user inputs numbers greater than the value of n. If the exception is caught, I'm trying to handle the error by having the user enter a "valid" value for n: a value that's less than the number of items in the vector.
Edit: But yeah, I noticed that the sign is wrong in the do-while loop's condition. I changed that. It works fine now.
Edit 2: I need to modify the program following these two guidelines now:
9. Modify the program from exercise 8 to write out an error if the result
cannot be represented as an int .
10. Modify the program from exercise 8 to use double instead of int . Also,
make a vector of double s containing the N–1 differences between adjacent values and write out that vector of differences.
I don't understand what it means by the N-1 differences between adjacent values, though. Could someone please explain?
// chapter5ex8.cpp : Defines the entry point for the console application.
// Osman Zakir
// 1 / 1 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 5 Exerice 8
// Program to ask user for a number n and then have them enter a sequence of
// numbers, stopping with '|'. The program will then print the sum of the first
// n numbers. The program print an error message if the user enters
// less than n numbers.
#include "../../std_lib_facilities.h"
#include <numeric>
int get_n();
bool clear_stream(istream& cin);
int main()
{
cout << "Please enter the numbers of values you want to sum: ";
int n = get_n();
int number = 0;
vector<int> numbers;
if (n > 0)
{
cout << "Please enter some integers (press '|' to stop): ";
while (!(cin.peek() == '|'))
{
cin >> number;
cin.ignore();
numbers.push_back(number);
if (cin.fail())
{
clear_stream(cin);
continue;
}
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
try
{
if (numbers.size() < n)
{
error("too few numbers entered!");
}
}
catch (const runtime_error &e)
{
cerr << "error: " << e.what() << '\n';
do
{
cout << "Please enter a value for n not less than the number values entered: ";
cin >> n;
cin.ignore();
}
while (n > numbers.size());
}
int sum = accumulate(numbers.cbegin(), (numbers.cbegin() + n), 0);
cout << "The sum of the first " << n << " numbers is " << sum << '\n';
try
{
if (sum > numeric_limits<int>::max())
{
error("The sum is too high");
}
}
catch (const runtime_error &e)
{
cerr << "error: " << e.what() << '\n';
keep_window_open();
return 1;
}
}
keep_window_open();
}
int get_n()
{
int n = 0;
cin >> n;
cin.ignore();
return n;
}
bool clear_stream(istream& cin)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
returntrue;
}
To detect if the input is a double, how about this?
and ofc, you also need to check against INT_MIN and INT_MAX -> http://www.cplusplus.com/reference/climits/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
usingnamespace std;
//write out an error if the result cannot be represented as an int .
int main()
{
double d;
cin >> d;
if (d - int(d))
{
cout << "error" << endl;
//if we are here, then the double minus the truncated int still had
//some remainder, so it cannot be represented as an int without
//losing precision.
}
return 0;
}
// chapter5ex8.cpp : Defines the entry point for the console application.
// Osman Zakir
// 1 / 1 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 5 Exerice 8
// Program to ask user for a number n and then have them enter a sequence of
// numbers, stopping with '|'. The program will then print the sum of the first
// n numbers. The program print an error message if the user enters
// less than n numbers.
#include "../../std_lib_facilities.h"
#include <numeric>
int get_n();
bool clear_stream(istream& cin);
int main()
{
cout << "Please enter the numbers of values you want to sum: ";
int n = get_n();
int number = 0;
vector<int> numbers;
if (n > 0)
{
cout << "Please enter some integers (press '|' to stop): ";
while (!(cin.peek() == '|'))
{
cin >> number;
cin.ignore();
numbers.push_back(number);
if (cin.fail())
{
clear_stream(cin);
continue;
}
}
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
try
{
if (numbers.size() < n)
{
error("too few numbers entered!");
}
}
catch (const runtime_error &e)
{
cerr << "error: " << e.what() << '\n';
do
{
cout << "Please enter a value for n not less than the number values entered: ";
cin >> n;
cin.ignore();
}
while (n > numbers.size());
}
int sum = accumulate(numbers.cbegin(), (numbers.cbegin() + n), 0);
cout << "The sum of the first " << n << " numbers is " << sum << '\n';
try
{
if (sum > numeric_limits<int>::max())
{
error("The sum is too high");
}
}
catch (const runtime_error &e)
{
cerr << "error: " << e.what() << '\n';
keep_window_open();
return 1;
}
}
keep_window_open();
}
int get_n()
{
int n = 0;
cin >> n;
cin.ignore();
return n;
}
bool clear_stream(istream& cin)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
returntrue;
}
Then you just need the climits header ->http://www.cplusplus.com/reference/climits/
Which btw, I think it get included indirectly by <iostream> so the code should work without any extra #include
1 2 3 4 5 6 7
longlong num;
cin >> num;
if(num < INT_MIN || num > INT_MAX )
{
//crash the users computer
}
std::numeric_limits<int>::max() wouldn't work? I'm trying to use that currently.
And why would you want to crash the user's computer? Just print an error message. The book also just says to print an error message of the sum of the N numbers the user asks for is too large to fit in an int.
Edit: For the N-1 differences, what am I doing wrong here?
1 2 3 4 5 6 7
for (unsigned i = 0; i < numbers.size(); ++i)
{
difference = numbers[i] - numbers[i - 1];
differences.push_back(difference);
cout << difference << ' ';
}
cout << '\n';
I'm getting an exception thrown. I'm guessing it's because std_lib_facilities.h adds range-checking in the vector's operator[], but I'm not sure where it's being triggered other than that the fact that it's somewhere in the code I've posted here.