The assignment requires three functions. The user enters digits 0-9 until they enter a 10, which stops input, and counts each number, then outputs how many of each number has been counted. It should only output if the user entered a number for it.
My only problem is that for every element in the array that the user doesn't use, Xcode counts it as a 0, so the final output has an abnormally large amount of zeros. Everything else works fine.
here is my code
#include <iostream>
using namespace std;
// counter function prototype
void count(int[], int, int []);
// print function prototype
void print(int []);
int main()
{
// define variables and initialize arrays
const int SIZE=100;
int numbers[SIZE], counter[10], input;
// for loop to set all counter elements to 0
for (int assign = 0; assign < 10; assign++)
{
counter[assign]=0;
}
// for loop to collect data
for (int index=0 ; input != 10 ; index++)
{
cout << "Enter a number 0-9, or 10 to terminate: ";
cin >> input;
// while loop to ensure input is 0-10
while (input < 0 || input > 10)
{
cout << "Invalid, please enter 0-9 or 10 to terminate: ";
cin >> input;
}
// if statements to sort input
if (input >= 0 && input <=9)
{
numbers[index] = input;
}
}
// call count function
count(numbers, SIZE, counter);
// call print function
print(counter);
return 0;
}
// counter function
void count(int numbers[], int SIZE, int counter[])
{
// for loop of counter
for (int index = 0 ; index < 10 ; index++)
{
// for loop of numbers
for (int tracker=0 ; tracker < SIZE ; tracker++)
{
// if statement to count each number
if (index == numbers[tracker])
{
counter[index]++;
}
}
}
return;
}
// print function
void print(int counter[])
{
// for loop to print each element
for (int index=0 ; index < 10 ; index++)
{
// if statement to only print numbers that were entered
if (counter[index] > 0)
{
cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
}
}
return;
}
What you're referring to as "XCode count[ing] as a 0" is actually just the uninitialized value. Given that you've decided to restrict the user's input to 0-9, an easy way of solving this dilemma would be, immediately after you size the array, to iterate through the array and set each value to -1.
Thereafter, when the user finishes their input, instead of just couting every single value, only print it with a conditional like the following:
if (counter[index] != -1)
{
cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
}
Note that this is the kind of use case that's much better suited to something like a linked list or a vector. As it stands, you're not doing anything to resize the array, or guard against overflow, so if the user attempts to enter more than 100 numbers, you'll run into serious problems.
First off, this isn't an answer to your exact question, but rather a suggestion on how to write your code in a much simpler form.
I'm not going to write this for you, as it's an assignment, and a rather simple one. Looks like you have a good handle on things as far as coding goes.
Consider this:
You need to allow the user to enter 0-10, and count all 0-9's. An array has indices, and a integer of array 10, would hold those 10 numbers you're counting by the indices. Now you just have some empty ints sitting around, so why not use them to count?
A code hint:
++numbers[input];
Second hint: Don't forget to initialize everything to zero.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
This program is a secret 5-digit code guessing game. Each digit of the code is between 0 and 9, and digits cannot repeat in the code. After entering a digit one at a time, the player receives feedback for each digit in the form of a symbol: *, +, or -.
Each symbol has a different meaning:
means the digit is in the code and it is in the correct position
means the digit is in the code but it is not in the correct position
means the digit is not in the code
I am having trouble with the search_array function, specifically what value should be in the function call for the parameter 't'.
Secondly, I can't get the second do-while loop to work correctly, I figured that these problems went hand-in-hand with each other.
This code is from a past assignment and the directions stated that we couldn't change any of the functions given to us, but that we could add variables and addtional functions as needed. I would like to adhere to these rules as much as possible.
I have tried multiple things to solve this issue, such as putting in the number of digits (5) and trying to put an array of all the numbers in the five digit code (which wouldn't work because t is an int). I put 'i' in there as a placeholder until I could find a solution.
Here is my current code:
#include <iostream>
using namespace std;
void game_instructions(int n);
bool contains_duplicates(int a[], int n);
bool search_array(int a[], int n, int t);
int main()
{
//Step 1: Declare your variables and constants
const int SIZE = 5; //this constant stores the length/size of the code
int randcode[SIZE]; //this array stores the code generated randomly by the computer
int guess[SIZE];
const int SIZE2 = 5;
int target[SIZE2]{ 1, 7, 4, 0, 9 };
//this array stores the code inputted by the player/user
//you may add more variables as needed
//Step 2: Output game instructions by calling function game_instructions
game_instructions(SIZE);
//Step 3: Generate a random code and store it in the array randcode one digit at a time.
//Each digit should be between 0 and 9 and should be stored as one array element
//Recall that rand() % 10 can be used to generate a number between 0 and 9
do
{
for (int i = 0; i < SIZE; i++)
{
randcode[i] = rand() % 10;
cout << randcode[i];
}
//Step 4: Repeat step 3 if the array randcode contains duplicates
//You must use function contains_duplicates to implement this step
} while (contains_duplicates(randcode, SIZE));
do
{
//Step 5: Ask the user for his guess and store it in the array guess.
//Read one digit at a time, validate it to make sure it is between 0 and 9, and store it as one array element
cout << "\nEnter your guess for the 5 digit code(one digit at a time) :\n";
for (int g = 0; g < SIZE; g++)
{
cout << "Enter digit " << (g + 1) << ":";
cin >> guess[g];
while (guess[g] < 0 || guess[g] > 9)
{
cout << "Your guess must be between 0 and 9.\n";
cout << "Please re-enter: ";
cin >> guess[g];
}
}
//Step 6: Output the array guess on a single line with a space after each element (see the sample output provided)
for (int g = 0; g < SIZE; g++)
{
cout << guess[g] << " ";
}
cout << "\n";
//Step 7: Compare the randomly generated code (randcode) with the user's guess (guess)
//and display feedback for each digit as: *, + or –, as explained below:
//For each digit in the user's guess do the following:
// If it matches the digit from the random code (both value and position), output *
// Otherwise, if it appears anywhere in the random code, output + (use function search_array here)
// Otherwise, output -
for (int i = 0; i < SIZE; i++)
{
if (guess[i] == randcode[i])
cout << "* ";
else if (search_array(randcode, 5, i))
{
cout << "+ ";
}
else
cout << "- ";
}
} while (guess != randcode);
//Step 8: Repeat steps 5,6,7 until all digits have been guessed correctly
//Step 9: Output congratulations message
cout << "\nGood job! You guessed the code!";
}
void game_instructions(int n)
//This function outputs the game instructions.
//Its parameter n represents the length of the code.
{
cout << "A random " << n << " digit code has been generated. You have to guess it. \n";
cout << "For every digit you will receive feedback in the form of *, + or - \n";
cout << " * means the digit is in the code and it is in the correct position.\n";
cout << " + means the digit is in the code but it is not in the correct position.\n";
cout << " - means the digit is not in the code.\n";
}
bool search_array(int a[], int n, int t)
//This function searches the array a (of size n) for a target value t.
//If t is found in the array the function returns true; otherwise it returns false.
{
for (int i = 0; i < n; i++)
{
if (a[i] == t) return true;
}
return false;
}
bool contains_duplicates(int a[], int n)
//This function searches the array a (of size n) and returns true if the array contains duplicates; otherwise, it returns false.
{
for (int i = 0; i < n; i++)
{
//compare element a[i] with all the remaining elements from index i+1 to n
for (int j = i + 1; j < n; j++)
{
if (a[i] == a[j]) return true;
}
}
return false;
}
You can get a lot of insight just from adding some debug output to the program.
Also, compiling with warnings will tell you:
SIZE2 and target variables are unused, and, mainly,
the array comparison guess != randcode is deprecated since C++20. You are better off changing it for a memcmp.
The call search_array(randcode, 5, i) looks for the value i in the array randcode (of size 5). But what that block is trying to achieve is knowing if a given number input by the user is in randcode; and that given number is guess[i].
For each of the numbers input by the user:
First, you check if guess[i] == randcode[i], i.e., if the user guessed both the number and the position. In that case a '*' is printed.
Then, in case they didn't, you check if at least the number is in the code to be guessed. In that case a '+' is printed; otherwise, a '-'.
[Demo]
Newer to coding and im stuck, Need to make a array thats stores 5 numbers (1-9), then i need to check that array for duplicates if there is duplicates i need to replace that number either with a whole new random line no duplicates (seems like the easier option) or just replace that one number,
after that wants me to get users 5 numbers guess store that in a array, display that array at the bottom along with these under each of the numbers
// The * = means the number is in the exact location
// The - = means the array does not contain that number
// The + = means the array contains the number but its not in the right location
All the arrays want the digits to be entered one at a time
repeat steps till user gets all the numbers to * then end game with completion msg.
My true problem lies with step 4 and step 7;
Below is the code ive been working on today but any help would be truly appreciated
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void game_instructions(int n);
bool search_array(int a[], int n, int t);
int main()
{
//Step 1: Declare your variables and constants
const int SIZE = 5; //this constant stores the length/size of the code
int randcode[SIZE]; //this array stores the code generated randomly by the computer
int guess[SIZE]; //this array stores the code inputted by the player/user
//you may add more variables as needed
//Step 2: Output game instructions by calling function game_instructions
game_instructions(SIZE);
//Step 3: Generate a random code and store it in the array randcode one digit at a time.
//Each digit should be between 0 and 9 and should be stored as one array element
//Recall that rand() % 10 can be used to generate a number between 0 and 9
srand(time(0));
for(int i=0;i<SIZE;i++)
randcode[i]= (rand() % 10); //Computers random 5 numbers generated
cout<<"\nRandom C-numbers::"<<endl;
for(int i=0;i<SIZE;i++)
cout<<randcode[i] << " ";
//Step 4: Repeat step 3 if the array randcode contains duplicates
//You must use function contains_duplicates to implement this step
//Step 5: Ask the user for his guess and store it in the array guess.
//Read one digit at a time, validate it to make sure it is between 0 and 9, and store it as one array element
for (int i=0; i<SIZE; i++) {
cout<<"\nEnter Digit "<< i+1 << ": ";
cin >> guess[i];}
cout << endl;
//Step 6: Output the array guess on a single line with a space after each element (see the sample output provided)
for (int n=0; n < SIZE; ++n) {
cout << guess[n] << " ";
}
//Step 7: Compare the randomly generated code (randcode) with the user's guess (guess)
//and display feedback for each digit as: *, + or –, as explained below:
//For each digit in the user's guess do the following:
// If it matches the digit from the random code (both value and position), output *
// Otherwise, if it appears anywhere in the random code, output + (use function search_array here)
// Otherwise, output -
//Step 8: Repeat steps 5,6,7 until all digits have been guessed correctly
//Step 9: Output congratulations message
cout << endl << endl;
cout << "Good job! You guessed the code!";
return 0;
}
void game_instructions(int n)
//This function outputs the game instructions.
//Its parameter n represents the length of the code.
{
cout << "A random " << n << " digit code has been generated. You have to guess it. \n";
cout << "For every digit you will receive feedback in the form of *, + or - \n";
cout << " * means the digit is in the code and it is in the correct position.\n";
cout << " + means the digit is in the code but it is not in the correct position.\n";
cout << " - means the digit is not in the code.\n";
}
bool search_array(int a[], int n, int t)
//This function searches the array a (of size n) for a target value t.
//If t is found in the array the function returns true; otherwise it returns false.
{
for (int i = 0; i < n; i++)
{
if (a[i] == t) return true;
}
return false;
}
bool contains_duplicates(int a[], int n)
//This function searches the array a (of size n) and returns true if the array contains duplicates; otherwise, it returns false.
{
for (int i = 0; i < n; i++)
{
//compare element a[i] with all the remaining elements from index i+1 to n
for (int j = i+1; j < n; j++)
{
if (a[i] == a[j]) return true;
}
}
return false;
}
I got most the side code done but im just stumped on how to get this array to match any help would be nice
Here is how I would implement the program to generate the number without duplicate:
Step3 would look like this:
int tempNumber;
int i = 0;
while (i < SIZE) {
tempNumber = (rand() % 10);
if (contains_duplicates(randcode, tempNumber, i) == false) {
// every time there is no duplicate we push and add i by 1;
randcode[i] = tempNumber; // Computers random 5 numbers generated
i++;
}
}
contains_duplicates function would look like this:
bool contains_duplicates(int arr[], int tempNum, int currentArrSize)
// This function searches the array a (of size n) and returns true if the
//array
// contains duplicates; otherwise, it returns false.
{
for (int j = 0; j <= currentArrSize; j++) {
// if the array[index] not equal generated number the loop will
//iterate again without going to the line below
if (arr[j] != tempNum) {
continue;
}
// if the array[index] equal the function will return true and end
//the function
// uncomment this to check how many time it duplicate (not
//necessary tho)
//cout << "if return true, this will appear"<< endl;
return true;
}
// if the loop is done and no duplicate, function will return false
return false;
}
With this method it is not necessary to do step 4 because we already prevent duplicate array!
Here is the last problem from your question which is step 7:
cout << endl;
for (int i = 0; i < SIZE; i++) {
if (guess[i] == randcode[i]) {
cout << "* ";
} else if (search_array(randcode, SIZE, guess[i])) {
cout << "+ ";
} else {
cout << "- ";
}
}
Seems like the problem has been solved, now try to implement step 8 by yourself, good luck :)
This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
The goal of this code is to pass an array through a function (which I'm already having a difficult time understanding). I went through with a pen and paper and traced the code and I think I just don't know enough to understand what's going wrong. All the test scores I throw in just push back a ridiculously large negative number. I'm not asking for you guys to do my homework because I really want to try and understand what I'm doing, but any help would really be appreciated right now.
#include <iostream>
//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);
int main() {
do {
int studentScores[4], size = 4, result;
string score;
cout << "This program will calculate the average of four diffrent exam scores." << endl;
for (int i = 0; i < size; i++) {
studentScores[i] = 0;
cout << "Please Enter Exam Score " << i + 1 << ": ";
getline(cin, score);
}
for (int i = 0; i < size; i++) {
result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
studentScores[i]++;
}
cout << "The Average Exam score is " << result << endl;
} while (runAgain());
system("pause");
return 0;
}
//function implementation
double average(int studentScores[], int size) {
for (int i = 0; i < size; i++) {
return (studentScores[i]++ / size);
}
}
bool runAgain(void) {
char userResponse;
cout << "\nWould you like to run again (y or n): ";
cin >> userResponse;
if (userResponse == 'y' || userResponse == 'Y')
return(true);
return(false);
}
First obvious bug:
int studentScores[4]
studentScores has 4 elements, numbered studentScores[0] through studentScores[3].
But your code accesses studentScores[4] in
result = (... + studentScores[4]) / ...
which doesn't exist (and doesn't access studentScores[0], which does).
Glad to try to help ya out without giving you the answer.
I'm gonna sprinkle some questions throughout your code that you should be asking yourself in future programs whenever you get unexpected output.
#include <iostream>
//function prototype
double average(int studentScores[], int size);
double studentScores[4];
bool runAgain(void);
int main() {
do {
int studentScores[4], size = 4, result;
string score;
/* Above, you declared a string to store the user's input in.
In C++, the string "4" DOES NOT equal the integer 4.
How will you handle the fact that the variable 'score' is of type
string, but you want to work with integers?
Is there an easy way to get rid of this issue? (hint: use cin)
*/
cout << "This program will calculate the average of four diffrent exam scores." << endl;
/* In the below for-loop, think about what the value of 'score' will be
after each iteration. (Hint, getline replaces the existing value of score).
Also, where is the code that saves the user's inputted numbers to an array?
Learn how to write values to an array http://www.cplusplus.com/doc/tutorial/arrays/
*/
for (int i = 0; i < size; i++) {
studentScores[i] = 0;
cout << "Please Enter Exam Score " << i + 1 << ": ";
getline(cin, score);
}
/* In the for-loop below, you already noticed that your array has random
values in it. The comment about the above for-loop should address that issue.
Equally important though is understanding what the heck is happening in this
loop below. After you fix the bug in the for-loop above (which will
get the values in the array to equal the user's inputs), you'll be faced
with issues in this loop below.
My advice is to understand what happens when the program
executes "studentScores[i]++". First, it gets the number in the array at
the ith+1 position, then it increments that number by 1. Cool, but what
are you doing with the result of that? It's not being put to use anywhere.
Also, note that because the array is never being updated,
the line above it just calculates the same number and stores it in 'result'
every iteration of the loop.
*/
for (int i = 0; i < size; i++) {
result = (studentScores[1] + studentScores[2] + studentScores[3] + studentScores[4]) / size;
studentScores[i]++;
}
cout << "The Average Exam score is " << result << endl;
} while (runAgain());
system("pause");
return 0;
}
// this function doesn't seem to be used, but understanding what
// is wrong with it will help you understand how to code.
// First, note that once a function hits 'return', it will
// never execute any more code in that function.
// So here, your return statement in the for-loop will prevent an
// actual loop from occuring (since the function will exit as soon as the first loop iteration is entered)
// Second, note that you are just getting the value in the array and adding 1 to it
// before dividing it by 'size', which is not the formula for an average.
double average(int studentScores[], int size) {
for (int i = 0; i < size; i++) {
return (studentScores[i]++ / size);
}
}
bool runAgain(void) {
char userResponse;
cout << "\nWould you like to run again (y or n): ";
cin >> userResponse;
if (userResponse == 'y' || userResponse == 'Y')
return(true);
return(false);
}
I hope these comments helped :) Keep at it!
Don't forget that arrays start at index 0. Trying to access studentScores[4]
will give you an unexpected number.
This question already has answers here:
cin >> fails with bigger numbers but works with smaller ones?
(4 answers)
Closed 5 years ago.
I have been following a course about algorithms on Coursera and I tried to put what I learned into code. This is supposed to be a "divide & conquer" algorithm and I hope that part is alright. I have a problem I encountered just messing around with it: everything works fine until I input a 12 digit number into the program. When I do that, it just ends the cin and outputs all the previous numbers sorted (blank space if no numbers are before). If you could, please tell me what's wrong if you spot the mistake. This is my code:
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
// setup global variable for the number of inversions needed
int inversions = 0;
// function to merge 2 sublists into 1 sorted list
vector<int> Merge_and_Count(vector<int>& split_lo, vector<int>& split_hi) {
// setup output variable -> merged, sorted list of the 2 input sublists
vector<int> out;
int l = 0;
int m = 0;
// loop through all the elements of the 2 sublists
for (size_t k = 0; k < split_lo.size() + split_hi.size(); k++) {
// check if we reached the end of the first sublist
if (l < split_lo.size()) {
// check if we reached the end of the second sublist
if (m < split_hi.size()) {
// check which element is smaller and sort accordingly
if (split_lo[l] < split_hi[m]) {
out.push_back(split_lo[l]);
l++;
}
else if (split_hi[m] < split_lo[l]) {
out.push_back(split_hi[m]);
m++;
inversions++;
}
}
else {
out.push_back(split_lo[l]);
l++;
inversions++;
}
}
else {
out.push_back(split_hi[m]);
m++;
}
}
return out;
}
// function that loops itself to split input into halves until it reaches the base case (1 element array)
vector<int> MergeSort_and_CountInversions(vector<int>& V) {
// if we reached the base case, terminate the loop and feed the output to the previous loop to be processed
if (V.size() == 1) return V;
// if we didn't reach the base case
else {
// continue halving the sublists
size_t const half_size = V.size() / 2;
vector<int> split_lo(V.begin(), V.begin() + half_size);
vector<int> split_hi(V.begin() + half_size, V.end());
// feed them back into the loop
return Merge_and_Count(MergeSort_and_CountInversions(split_lo), MergeSort_and_CountInversions(split_hi));
}
}
// main function of the app, runs everything
int main()
{
// setup main variables
int input;
vector<int> V;
// get input
cout << "Enter your numbers to be sorted (enter Y when you wish to proceed to the sorting)." << endl;
cout << "Note: do NOT use duplicates (for example, do not input 1 and 1 again)!" << endl;
while (cin >> input)
V.push_back(input);
cout << "\nThe numbers you chose were: " << endl;
for (size_t i = 0; i < V.size(); i++)
cout << V[i] << " ";
// get sorted output
vector<int> sorted = MergeSort_and_CountInversions(V);
cout << "\n\nHere are your numbers sorted: " << endl;
for (size_t j = 0; j < sorted.size(); j++)
cout << sorted[j] << " ";
// show number of inversions that were needed
cout << "\n\nThe number of inversions needed were: " << inversions << endl;
return 0;
}
12 decimal digits is too long to fit into a 32-bit number, which is how int is usually represented. Reading that number using >> therefore fails and cin >> input converts to a false value, which terminates the loop.
See operator >> documentation for details of handling failure modes.
You can get the maximum number of base-10 digits that can be represented by the type using the std::numeric_limits::digits10 constant:
std::cout << std::numeric_limits<int>::digits10 << '\n';
Chances are the maximum number of significant digits for type int is 9, and you try to supply 12 via standard input. The program doesn't crash, the condition of (cin >> input) simply evaluates to false.
12 digits is too much for 32-bit integer, try to use as unsigned long long int, check these limits:
http://www.cplusplus.com/reference/climits/
write a program that let's the user enter 10 numbers into an array. The program should then display the largest number as and the smallest number stored in the array.
I am very confused on this question that was on a previous exam and will be on the final. Any help would be appreciated! This is what I had on the test and got 3/15 points, and the code was almost completely wrong but I can post what I had if necessary, thanks! For creating the array, i can at least get that started, so like this?
#include <iostream>
using namespace std;
int main()
{
int array(10); // the array with 10 numbers, which the user will enter
cout << "Please enter 10 numbers which will be stored in this array" << endl;
cin >> array;
int smallest=0; //accounting for int data type and the actual smallest number
int largest=0; //accounting for int data type and the actual largest number
//-both of these starting at 0 to show accurate results-
And then on my test, i started using for loops and it got messy from there on out, so my big problem here i think is how to actually compare/find the smallest and largest numbers, in the best way possible. I'm also just in computer science 1 at university so we keep it pretty simple, or i like to. We also know binary search and one other search method, if either of those would be a good way to use here to write code for doing this. Thanks!
Start by declaring an array correctly. int array(10) initializes a single integer variable named array to have the value 10. (Same as saying int array = 10)
You declare an array of 10 integers as follows:
int array[10];
Anyway, two simple loops and you are done.
int array[10];
cout << "Enter 10 numbers" << endl;
for (int x = 0; x < 10; x++)
{
cin >> array[x];
}
int smallest=array[0];
int largest=array[0];
for (int x = 1; x < 10; x++)
{
if (array[x] < smallest)
{
smallest = array[x];
}
else if (array[x] > largest)
{
largest = array[x];
}
}
cout << "Largest: " << largest << endl;
cout << "Smallest: " << smallest << endl;
You can actually combine the two for loops above into a single loop. That's an exercise in an optimization that I'll leave up to you.
In this case, you don't actually have to do a binary search, or search the array. Since you will be receiving the input directly from the user, you can keep track of minimum and maximum as you encounter them, as show below. You know the first number you receive will be both the min and max. Then you compare the next number you get with those ones. If it's bigger or smaller, you store it as the max or min respectively. And then so on. I included code to store the number in an array, to check errors and to output the array back to the user, but that's probably not necessary on an exam due to the limited time. I included it as a little bit of extra info for you.
#include <cctype> // required for isdigit, error checking
#include <cstdlib> // required for atoi, convert text to an int
#include <iostream> // required for cout, cin, user input and output
#include <string> // required for string type, easier manipulation of text
int main()
{
// The number of numbers we need from the user.
int maxNumbers = 10;
// A variable to store the user's input before we can check for errors
std::string userInput;
// An array to store the user's input
int userNumbers[maxNumbers];
// store the largest and smallest number
int max, min;
// Counter variables, i is used for the two main loops in the program,
// while j is used in a loop for error checking
int i;
unsigned int j;
// Prompt the user for input.
std::cout << "Please enter " << maxNumbers << " numbers: " << std::endl;
// i is used to keep track of the number of valid numbers inputted
i = 0;
// Keep waiting for user input until the user enters the maxNumber valid
// numbers
while (i < maxNumbers)
{
// Get the user's next number, store it as string so we can check
// for errors
std::cout << "Number " << (i+1) << ": ";
std::cin >> userInput;
// This variable is used to keep track of whether or not there is
// an error in the user's input.
bool validInput = true;
// Loop through the entire inputted string and check they are all
// valid digits
for (j = 0; j < userInput.length(); j++)
{
// Check if the character at pos j in the input is a digit.
if (!isdigit(userInput.at(j)))
{
// This is not a digit, we found an error so we can stop looping
validInput = false;
break;
}
}
// If it is a valid number, store it in the array of
// numbers inputted by the user.
if (validInput)
{
// We store this number in the array, and increment the number
// of valid numbers we got.
userNumbers[i] = atoi(userInput.c_str());
// If this is the first valid input we got, then we have nothing
// to compare to yet, so store the input as the max and min
if (i == 0)
{
min = userNumbers[i];
max = userNumbers[i];
}
else {
// Is this the smallest int we have seen?
if (min < userNumbers[i])
{
min = userNumbers[i];
}
// Is this the largest int we have seen?
if (max < userNumbers[i])
{
max = userNumbers[i];
}
}
i++;
}
else
{
// This is not a valid number, inform the user of their error.
std::cout << "Invalid number, please enter a valid number." << std::endl;
}
}
// Output the user's numbers to them.
std::cout << "Your numbers are: " << userNumbers[0];
for (i = 1; i < maxNumbers; i++)
{
std::cout << "," << userNumbers[i];
}
std::cout << "." << std::endl;
// Output the min and max
std::cout << "Smallest int: " << min << std::endl;
std::cout << "Largest int: " << max << std::endl;
return 0;
}