Sum of a vector of integers - c++

I created a program that let's the user input up to 10 integers and then it will print out the sum of the inputted integers. However I want to stop the program when the user tries to input more than 10 integers or when the user types in "DONE". I didn't really get it to work because when the user types in something other than an integer (including the string "DONE"), it will stop. I only want it to stop when the user types in "DONE". If the user types in something like "Hello" I want the program to crash.
This is how it should look:
Enter up to 10 numbers:
12
12
4
DONE
The sum of the integers is: 28
What's wrong with my code? I am referring to my void read_numbers function. As I mentioned, I want it to stop ONLY when the user inputs the string "DONE" or when the user inputs more than 10 integers.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Number_Type {
vector<int> numbers;
};
void read_numbers(Number_Type& number) {
int digit{};
string line;
// char space = ' ';
while ((line != "DONE") && (number.numbers.size() != 10)) {
cin >> digit;
getline(cin, line);
number.numbers.push_back(digit);
}
}
int number_sum(Number_Type const& number) {
int sum{};
for (int i{}; i < number.numbers.size(); ++i) {
sum += number.numbers[i];
}
return sum;
}
int main() {
Number_Type number;
cout << "Enter up to 10 numbers: " << endl;
read_numbers(number);
cout << "The sum of the integers is: " << number_sum(number);
}

Fist you have to read all your inputs as strings. Then you can use std::from_chars to check if your input was a valid integer (without having to do exception handling, which std::stoi will need). Example here (live demo https://onlinegdb.com/UANchB1mn)
#include <iostream>
#include <string>
#include <vector>
#include <charconv>
auto read_numbers(const std::size_t max_numbers)
{
std::vector<int> values;
int value{};
std::string input;
do
{
std::cout << "Enter number " << values.size() + 1 << " of " << max_numbers << " (or DONE to stop) : ";
std::cin >> input;
// std::stoi is an option but then you would need do exception handling
auto result = std::from_chars(input.data(), input.data() + input.size(), value);
if (result.ec == std::errc())
{
values.push_back(value);
}
}
while ((input != "DONE") && (values.size() < max_numbers));
return values;
}
int main()
{
auto values = read_numbers(3);
std::cout << "you entered : ";
for (const auto value : values)
{
std::cout << value << " ";
}
return 0;
}

Related

how to keep storing users inputs in a while loop in c++

The user will enter a list of numbers. The user should enter as many numbers as the user wishes. All the numbers should be stored in a variable, I am not trying to add them all up.
#include <iostream>
using namespace std;
int main()
{
// declare variables
double number,listOfNumbers;
bool condition;
cout << "Enter a starting number: ";
cin >> number;
condition = true;
while (condition)
{
if(number > 0)
{
cout << "Enter another number (type 0 to quit): ";
listOfNumbers = number;
cin>>listOfNumbers;
}
else
{
condition=false;
}
}
cout << listOfNumbers;
return 0;
}
Use a std:vector to hold the numbers, eg:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// declare variables
double number;
vector<double> listOfNumbers;
cout << "Enter numbers (type 0 to quit): ";
while ((cin >> number) && (number != 0))
{
listOfNumbers.push_back(number);
}
for(number : listOfNumbers)
cout << number << ' ';
return 0;
}
Some small modifications and the use of a std::listor std::vector to store the values, the vector will grow dynamicly as you run the program and relocate if it runs out of space, the list will allocate space for every new item both works here.
I also never use using namespace std although it is very common in tutorials to do.
The syntax auto const &i in last for loops requires some of the later C++ standards it will give you a unmutable reference to the item.
#include <iostream>
#include <list>
int main() {
// declare variables
double number;
std::list<double> listOfNumbers;
bool condition;
std::cout << "Enter a starting number: ";
std::cin >> number;
condition = true;
while (condition) {
if (number > 0) {
listOfNumbers.push_back(number);
std::cout << "Enter another number (type 0 to quit): ";
std::cin >> number;
} else {
condition = false;
}
}
for (auto const &i : listOfNumbers) {
std::cout << i << std::endl;
}
return 0;
}

How to store intergers to an array without knowing how many values are initially inputted

#include <iostream>
#include<cmath>
using namespace std;
int main(){
int grades[10];
cout << "Enter list: ";
int count = 0;
int current = 0;
while (current >= 0){
cin >> current;
grades[count] = current;
count += 1;
}
cout << grades[0];
}
Should output the first int in the array but instead outputs nothing after entering a list of numbers separated by spaces (less than 10 total). Ideally, it should output the entire array but I can't figure out why it won't just output the first value of the array. I suspect it's something to do with while (current >= 0). If so then im wondering how I can check if there are no more inputs left in the stream.
An array such as int grades[10] in your code cannot be resized in standard C++.
Instead, use a standard container - such as std::vector - which is designed to be resized at run time
#include <vector>
#include <iostream>
int main()
{
std::vector<int> grades(0); // our container, initially sized to zero
grades.reserve(10); // optional, if we can guess ten values are typical
std::cout << "Enter list of grades separated by spaces: ";
int input;
while ((std::cin >> input) && input > 0) // exit loop on read error or input zero or less
{
grades.push_back(input); // adds value to container, resizing
}
std::cout << grades.size() << " values have been entered\n";
// now we demonstrate a couple of options for outputting all the values
for (int i = 0; i < grades.size(); ++i) // output the values
{
std::cout << ' ' << grades[i];
}
std::cout << '\n';
for (const auto &val : grades) // another way to output the values (C++11 and later)
{
std::cout << ' ' << val;
}
std::cout << '\n';
}

Modern Way of checking if C++ input is integer or not

I want to add the check-in my c++ code that user can not enter not integral values in reg. If he inputs, he is prompted again. I saw the solutions in the stack overflow that was of 2011 (How to check if input is numeric in C++). Is there some modern or good way now or is it same?
I tried using ifdigit() in ctype.h
// Example program
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
int x;
cout<<"Type X";
cin>>x;
if(!isdigit(x))
{
cout<<"Type Again";
cin>>x;
}
}
but it didnt worked
here is my actual problem where I want to add check.
cout << "Type Reg # of Student # " << i + 1 << endl;
do
{
cin >> arr[i][j];
} while (arr[i][j] < 999 || arr[i][j] > 9999);
where i and j are in dec. in for loop. I just want to add check that input is not string or something like this. Cant rely on 2011 answer
Check out the below example.
All the magic happens inside to_num(), which will handle white space before and after the number.
#include <iostream>
#include <sstream>
#include <string>
#include <tuple>
auto to_num(const std::string& s)
{
std::istringstream is(s);
int n;
bool good = (is >> std::ws >> n) && (is >> std::ws).eof();
return std::make_tuple(n, good);
};
int main()
{
int n;
bool good;
std::cout << "Enter value: ";
for(;;)
{
std::string s;
std::getline(std::cin, s);
std::tie(n, good) = to_num(s);
if(good) break;
std::cout << s << " is not an integral number" << std::endl;
std::cout << "Try again: ";
}
std::cout << "You've entered: " << n << std::endl;
return 0;
}
Explanation of what's going on inside to_num():
(is >> std::ws >> n) extracts (optional) leading white space and an integer from is. In the boolean context is's operator bool() will kick in and return true if the extraction was successful.
(is >> std::ws).eof() extracts (optional) trailing white space and will return true if there is no garbage at the end.
UPDATE
Here is a slightly cleaner version that uses Structured binding declaration and Class template argument deduction available in c++17:
#include <iostream>
#include <sstream>
#include <string>
#include <tuple>
auto to_num(const std::string& s)
{
std::istringstream is(s);
int n;
bool good = (is >> std::ws >> n) && (is >> std::ws).eof();
return std::tuple(n, good); // look ma, no make_tuple
};
int main()
{
std::cout << "Enter value: ";
for(;;)
{
std::string s;
std::getline(std::cin, s);
auto [n, good] = to_num(s); // structured binding
if(good)
{
std::cout << "You've entered: " << n << std::endl;
break;
}
else
{
std::cout << s << " is not an integral number" << std::endl;
std::cout << "Try again: ";
}
}
return 0;
}
If you properly handle errors, you'll end up with a prompt / input loop that looks something like this:
#include <iostream>
#include <limits>
int getInput() {
while (true) {
std::cout << "Please enter a number between 80 and 85: ";
int number = 0;
std::cin >> number;
std::cout << "\n";
if (std::cin.eof()) {
std::cout << "Unexpected end of file.\n";
std::cin.clear();
continue;
}
if (std::cin.bad() || std::cin.fail()) {
std::cout << "Invalid input (error reading number).\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
if (number < 80 || number > 85) {
std::cout << "Invalid input (number out of range).\n";
continue;
}
return number;
}
// unreachable
return 0;
}
int main() {
int number = getInput();
std::cout << number << std::endl;
}
We can omit the range check if we don't need it.
We handle std::cin.eof() (e.g. user presses ctrl+Z on Windows) separately from the other conditions, since for eof there's nothing to ignore.
This follows the standard C++ stream behavior for whitespace and number conversion (i.e. it will accept inputs with extra whitespace, or inputs that only start with numeric values).
If we want more control over what we want to accept, or don't want conversion to depend on the locale, we have to use std::getline to read input from std::cin, and then do the string conversion ourselves (either with std::stringstream as in Innocent Bystander's answer, or using std::strtol, or std::from_chars).

My 1st Quiz - Issue (C++) [duplicate]

I was typing this and it asks the user to input two integers which will then become variables. From there it will carry out simple operations.
How do I get the computer to check if what is entered is an integer or not? And if not, ask the user to type an integer in. For example: if someone inputs "a" instead of 2, then it will tell them to reenter a number.
Thanks
#include <iostream>
using namespace std;
int main ()
{
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}
You can check like this:
int x;
cin >> x;
if (cin.fail()) {
//Not an int.
}
Furthermore, you can continue to get input until you get an int via:
#include <iostream>
int main() {
int x;
std::cin >> x;
while(std::cin.fail()) {
std::cout << "Error" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cin >> x;
}
std::cout << x << std::endl;
return 0;
}
EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. One needs not clear/ignore the input stream in that situation. Verifying the string is just numbers, convert the string back to an integer. I mean, this was just off the cuff. There might be a better way. This won't work if you're accepting floats/doubles (would have to add '.' in the search string).
#include <iostream>
#include <string>
int main() {
std::string theInput;
int inputAsInt;
std::getline(std::cin, theInput);
while(std::cin.fail() || std::cin.eof() || theInput.find_first_not_of("0123456789") != std::string::npos) {
std::cout << "Error" << std::endl;
if( theInput.find_first_not_of("0123456789") == std::string::npos) {
std::cin.clear();
std::cin.ignore(256,'\n');
}
std::getline(std::cin, theInput);
}
std::string::size_type st;
inputAsInt = std::stoi(theInput,&st);
std::cout << inputAsInt << std::endl;
return 0;
}
Heh, this is an old question that could use a better answer.
User input should be obtained as a string and then attempt-converted to the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”
Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string→type conversion and observe the success or failure:
template <typename T>
auto string_to( const std::string & s )
{
T value;
std::istringstream ss( s );
return ((ss >> value) and (ss >> std::ws).eof()) // attempt the conversion
? value // success
: std::optional<T> { }; // failure
}
Using the optional type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.
Here is an example of using it:
int n;
std::cout << "n? ";
{
std::string s;
getline( std::cin, s );
auto x = string_to <int> ( s );
if (!x) return complain();
n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";
limitations and type identification
In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.
The next caveat is that some types subsume others. For example, if you are trying to distinguish between int and double, check for int first, since anything that converts to an int is also a double.
There is a function in c called isdigit(). That will suit you just fine. Example:
int var1 = 'h';
int var2 = '2';
if( isdigit(var1) )
{
printf("var1 = |%c| is a digit\n", var1 );
}
else
{
printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
printf("var2 = |%c| is a digit\n", var2 );
}
else
{
printf("var2 = |%c| is not a digit\n", var2 );
}
From here
If istream fails to insert, it will set the fail bit.
int i = 0;
std::cin >> i; // type a and press enter
if (std::cin.fail())
{
std::cout << "I failed, try again ..." << std::endl
std::cin.clear(); // reset the failed state
}
You can set this up in a do-while loop to get the correct type (int in this case) propertly inserted.
For more information: http://augustcouncil.com/~tgibson/tutorial/iotips.html#directly
You can use the variables name itself to check if a value is an integer.
for example:
#include <iostream>
using namespace std;
int main (){
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
if(firstvariable && secondvariable){
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}else{
cout << "\n[ERROR\tINVALID INPUT]\n";
return 1;
}
return 0;
}
I prefer to use <limits> to check for an int until it is passed.
#include <iostream>
#include <limits> //std::numeric_limits
using std::cout, std::endl, std::cin;
int main() {
int num;
while(!(cin >> num)){ //check the Input format for integer the right way
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "Invalid input. Reenter the number: ";
};
cout << "output= " << num << endl;
return 0;
}
Under C++11 and later, I have the found the std::stoi function very useful for this task. stoi throws an invalid_argument exception if conversion cannot be performed. This can be caught and handled as shown in the demo function 'getIntegerValue' below.
The stoi function has a second parameter 'idx' that indicates the position of the first character in the string after the number. We can use the value in idx to check against the string length and ascertain if there are any characters in the input other than the number. This helps eliminate input like 10abc or a decimal value.
The only case where this approach fails is when there is trailing white space after the number in the input, that is, the user enters a lot of spaces after inputting the number. To handle such a case, you could rtrim the input string as described in this post.
#include <iostream>
#include <string>
bool getIntegerValue(int &value);
int main(){
int value{};
bool valid{};
while(!valid){
std::cout << "Enter integer value: ";
valid = getIntegerValue(value);
if (!valid)
std::cout << "Invalid integer value! Please try again.\n" << std::endl;
}
std::cout << "You entered: " << value << std::endl;
return 0;
}
// Returns true if integer is read from standard input
bool getIntegerValue(int &value){
bool isInputValid{};
int valueFromString{};
size_t index{};
std::string userInput;
std::getline(std::cin, userInput);
try {
//stoi throws an invalid_argument exception if userInput cannot be
//converted to an integer.
valueFromString = std::stoi(userInput, &index);
//index being different than length of string implies additional
//characters in input that could not be converted to an integer.
//This is to handle inputs like 10str or decimal values like 10.12
if(index == userInput.length()) isInputValid = true;
}
catch (const std::invalid_argument &arg) {
; //you could show an invalid argument message here.
}
if (isInputValid) value = valueFromString;
return isInputValid;
}
You could use :
int a = 12;
if (a>0 || a<0){
cout << "Your text"<<endl;
}
I'm pretty sure it works.

Input values into a vector until the end of input?

So I want the user to input something like this:
0 15 72 34 92 8
and I want to fill a vector of integers with these numbers.
Here is what I have:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> V;
cout << "Please enter the numbers separated by \n";
cout << "spaces, then press the \"Enter\" key.\n\n";
int temp;
while (cin >> temp)
{
V.push_back(temp);
}
// The programs gets to this point and continuously asks for input
// Print the vector
cout << "The vector contains [ ";
for(int i = 0; i < V.size(); i++)
cout << V.at(i) << " ";
cout << "], ";
}
Modify your code based on this example. It takes input from user until user enters -1.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int number;
vector<int> userInput;
do
{
cout << "Enter a number (-1 to quit): ";
cin >> number;
userInput.push_back(number);
} while (number != -1);
for (vector < int >::iterator it = userInput.begin(); it < userInput.end() - 1; it++)
{
cout << endl << *it;
}
system("pause");
return 0;
}
First, read the entire line as a string using getline and after that fetch every integer and push it into the integer array.
vector<int> v;
string buffer;
int data;
getline(cin, buffer);
istringstream iss(buffer);
while (iss >> data)
v.push_back(data);