Displaying a character based on integer entered by user - c++

I am sure this will seem very novice to many on here but I am currently trying to learn C++ and have an in depth full understanding to apply my knowledge in the real world.
The Problem Description:
Write a program that graphically depicts an integer’s magnitude by using asterisk, creating a
histogram. Hint: The inner loop handles the printing of the asterisk and the outer loop handles
exciting until zero is entered. Make sure you don’t accept negative numbers.
Sample run:
Enter a positive integer (0 to quit): 5
*****
Enter a positive integer (0 to quit): 8
********
Enter a positive integer (0 to quit): -5
Enter a positive integer (0 to quit): -10
Enter a positive integer (0 to quit): 15
***************
Enter a positive integer (0 to quit): 0
Good Bye!
My Current Code (I know this isn't right by any means, but helps demonstrate my thinking, I know you need to use a nested loop to answer this properly.):
#include <iostream>
using namespace std;
int main()
{
int ast; //Number of asterisk wanted to be displayed
char asts='*'; //Actual display coressponding to asterisk
cout<<"Enter a positive integar, (0 to quit)"<<endl;
cin>>ast;
while(ast!=0)
{
if(ast>0) // Ensuring no negative integars are entered
{
asts=ast;
cout<<asts<<endl;
cout<<endl;
}
else //Display if negative or other invalid data is entered
cout<<"Invalid Data, negative values are not accepted, try a positive integar or 0 to quit"<<endl;
cout<<"Do you want to continue? If so, enter another integar (0 to quit)"<<endl;
cin>>ast;
}
cout<<"Thank you for using the program."<<endl;
return(0);
}
Thank you for the help ahead of time!
-Colin

The basic idea is (with pseudo-code):
get number of asterisks
while number is not zero:
if number is negative:
output error message
else:
do number times:
output *
output newline
get number of asterisks
Your nested loops there are while number is not zero and do number times.
However, one of the earliest skills you should learn as a developer is to properly assign tasks to specific pieces of code (methods, functions, libraries and so on). In particular, it's a good idea to modularise your code so that each piece has a well defined purpose, then build the "upper" layers out of those pieces.
To that end, this is how I would approach the problem. First, define the functions that would be useful in this case.
Start with getAsterCount() which is responsible for asking the user how many asterisks they want and verifying that it's valid (asking again and again, until it is). For example:
#include <iostream>
int getAsterCount() {
// Until we get valid response.
for(;;) {
int count;
// Get value, checking for error, forcing exit if so.
std::cout << "Enter the number of asterisks, zero to exit: ";
if (! (std::cin >> count)) {
std::cout << "*** ERROR: could not read number\n";
return 0;
}
// Any non-negative value is allaowed.
if (count >= 0) {
return count;
}
std::cout << "That was less than zero, try again.\n";
}
}
Once that's in place, you never have to worry again about the user providing invalid information for this program, since this function will capture it (and you can call it from anywhere, as shown in the main() function below.
Next, provide a function that will actually output the asterisks, based on the count you now have:
void outputAster(int count) {
// Simple loop for asterisks then new line.
for (int i = 0; i < count; ++i) {
std::cout << '*';
}
std::cout << '\n';
}
With that in hand, your main code becomes the conceptually much simpler:
int main() {
int count = getAsterCount();
while (count > 0) {
outputAster(count);
count = getAsterCount();
}
std::cout << "Thank you for using the program. Now get off my lawn.\n";
}

Right now you are trying to do:
asts=ast;
Which doesn't make much sense, as this will only assign the entered integer to asts.
To print the magnitude in * you need to loop from 0 to the inputted integer and print out an asterix every time:
for(int i = 0; i < ast; i++) {
std::cout << "*";
}
std::cout << "\n";
Output:
Enter a positive integar, (0 to quit)
5
*****
Do you want to continue? If so, enter another integar (0 to quit)
3
***
Do you want to continue? If so, enter another integar (0 to quit)
5
*****
Do you want to continue? If so, enter another integar (0 to quit)
0

I like a somewhat different approach, without a loop.
char asts[] = “*********\n”;
After checking that the input value is in range, just write out the tail of the string:
std::cout << (asts + 9 - ast);

Related

c++ program to check entered number by user

I am new to programming, started with C++ quite recently and I use CLion IDE.
I need to solve something, but I am not sure how exactly and I need your help with a basic C++ console program.
if the user enters a ten-digit number and the fifth number is one, the output should be this word - "zadochno".
if the user enters a ten-digit number and the fifth number is two, the output should be this word - "redovno".
The user is expected to enter 2101162235 or similar.
In any case, the fifth element should be either 1 or 2.
Examples:
Option 1: input> 2101162235 -> output string "zadochno"
Option 2: input> 2101262235 -> output string "redovno"
I am able to only partially create the program:
#include<iostream>
int number;
cout << "Please, enter number: ";
cin > number;
//I believe there should be an if statement or for loop here:
if(){
}
Can you please help me?
You can take the input from the user as std::string and then check if the element at index 4 is 1 or 2 as shown below:
#include <iostream>
#include <string>
int main()
{
std::string input;
//take input from user
std::getline(std::cin, input);
//check if the 5th letter(at index 4 since indexing starts with 0) is '1' or '2'
if(input.at(4) == '1')
{
std::cout<< "zadochno"<<std::endl;
}
else if(input.at(4) == '2')
{
std::cout << "redovno"<<std::endl;
}
//this below shown for loop is optional. If you're sure that the user input contains only digits then you can skip/remove this for loop.
for(int i = 0; i < input.size(); ++i)
{
//check if the all the characters are digits of a number
if(std::isdigit(input[i]))
{
;//std::cout<<"yes digit";
}
else
{
std::cout<<"Please enter a valid number"<<std::endl;
}
}
return 0;
}
The output of the above program can be seen here.
Assuming the user does enter a 10 digit number (ie you don't need to check if they enter eg "foo" or "bar3000"), you can do the following:
Read the input as a std::string, not as int. User input is a string of characters always. Only if you need it you can get it converted to an integer. You do not need it as int. The n-th character of a std::string called user_input is user_input[n]. You just need to check whether the character in the middle is either '1' or '2'.
If you do need to check that the user did enter digits, you could use std::isdigit.

Need help understanding what's going on in my while loop

My program executes just fine, but I have questions about how my while loop is set up.
I know the Boolean values for true and false are 1 and 0, respectively, but I'm not understanding why my output displays the even and odd numbers backwards (to my understanding, it's backwards). Simply put, I don't understand why if ( number % 2 == 0 ) would display that a number is even and when I change it to 1, it displays odd. I'm reading this line as, if (even number equals to false). I don't know if that's where I'm going wrong. What's the correct way to read this line?
The way I have my code set up now displays the numbers correctly, I'm just not understanding why. Can anyone help?
// Program indefinitely displays an even
// or odd number until a negative number
// is entered.
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Please enter a number: ";
cin >> number;
while ( number >= 0 )
{
if ( number % 2 == 0 )
{
cout << number << " is even \n";
cout << "Please enter a number: ";
cin >> number;
}
else
{
cout << number << " is odd \n";
cout << "Please enter a number: ";
cin >> number;
}
}
cout << "Thank you. \n";
return 0;
}
number % 2 is 0 if number divides 2 (i.e. is even), 1 if number is positive and does not divide 2 (i.e. is odd), and -1 if number is negative and does not divide 2 (i.e. is odd). (The last point must be the case from C++11 onwards).
So, since 0 == 0 is true, number % 2 == 0 is true if, and only if, number is even.
So you've written if ( number % 2 == 0 ) to trap all even cases, and the else traps the odd cases.
Testing if ( number % 2 == 1 ) is only a test for positive oddness, but older C++ standards allow this to be true for negative number.

Trying to check array data with if statement

I'm trying to check if the users input data falls within the range i want. so far i have it like this:
void getPlayersNumbers(int playerArray[], int size) {
cout << "Please enter 5 numbers between 1-5\n";
for (int i = 0; i < size; i++) {
cin >> playerArray[i];
if (playerArray[i] < 1 || playerArray[i] > 5) {
cout << "Please enter numbers between 1 and 5\n";
}
}
}
now if they enter a number less than 1 or greater than 5 the message shows up. The only problem is i can still only input 5 numbers total even if one of them is out of the range and the message shows up. what should i do so that the function will only end if they enter 5 numbers that are within my set range?
Consider what you are doing:
You get input.
You put that input into your array.
You check whether input was smaller than 1 or bigger than 5
Go back to 1.

C++: Tracking iterations in code (after n iteration do x) / User input

I had a question in regards to a beginner assignment I was working on. The initial assignment requires me to make a program that asks the user to enter any number other than 5 until the user enters 5. If they enter 5 the program will alert them saying they input 5.
The next part of the assignment requires me to make a condition where after 10 iterations or 10 inputs of a non 5 value, the program messages the user and exits the program.
I finished the first part but had trouble with the second part. I searched stackoverflow and found something about the "get" function, but I'm not sure how to implement it correctly. How would I track the number of inputs or iterations and make a condition to where after n number of successful iterations the program exits?
Also , how would I make a condition to where if the user inputs a character instead of an integer the program warns the user and exits?
Thanks for the help. Here is the code I have written so far.
// This program works, however, if user inputs a character or a very large number
//then the program malfunctions.
// Learn more about the get function.
#include <iostream>
using namespace std;
int main()
{
int inpt;
cout << "Please input any number other than 5.\n";
cin >> inpt;
while (inpt != 5)
{
cout << "Please input another number other than 5.\n";
cin >> inpt;
}
if (inpt = 5)
{
cout << "Hey! You weren't supposed to enter 5!";
}
return 0;
}
you need to add a counter
int count = 0;
increment it each time round the loop
cout << "Please input another number other than 5.\n";
cin >> inpt;
count++;
and stop if the count gets too big
if(count>10) break;
you could also change your while condition
Note
if(inpt = 5) doesnt do what you think, you mean inpt == 5

unable to enter n in the below code( cin>>n)

/**
Write a program that reads a series of numbers and stores them in a vector. After the user inputs all the numbers he or she wishes to, ask how many of the numbers the user wants to sum. For an answer N. print the sum of the first N elements of the vector. For example: "Please enter some numbers (press 'I' at prompt to stop ) : " 12 23 13 24 15 "Please enter how many of the numbers you wish to sum, starting from the first:" 3 "The sum of the first 3 numbers : 12, 23, and 13 is 48." Handle all inputs. For exam ple, make sure to give an error message if the user asks for a sum of more numbers than there are in the vector.
**/
#include<iostream>
#include<vector>
using namespace std;
int main()
{
try
{
vector<int> numbers;
int num;
cout<<"Now enter the numbers";
while(cin>>num)
numbers.push_back(num);
int n,sum=0;
cout << "Enter the nth number to find sum of elements till n : ";
cin>>n;
if(n >numbers.size())
throw 66;
for(int i=0;i<n;i++)
sum+=numbers[i];
cout << "sum is "<<sum;
return 0;
}
catch(int k)
{
cerr<<"Error "<<k;
return -1;
}
}
So , when I enter EOF , CTRL+D , the program terminates. I am not sure where it is going wrong. I even tried to debug using gdb(with the help from an online tutorial) . It didn't just work out . can someone tell me what's wrong with the code ?
You are not checking if you actually read anything.
Consider this little test program:
#include <iostream>
int main()
{
std::cout << "std::cin is " << (std::cin ? "ready" : "done") << "\n";
int n = -42;
std::cin >> n;
std::cout << n << "\n";
std::cout << "std::cin is " << (std::cin ? "ready" : "done") << "\n";
n = -42;
std::cin >> n;
std::cout << n << "\n";
std::cout << "std::cin is " << (std::cin ? "ready" : "done") << "\n";
}
The output, when fed with an empty standard input (which is equivalent to immediately declaring its end with ctrl+d) is:
std::cin is ready
-42
std::cin is done
-42
std::cin is done
As you can see, n is never changed, as there is never a new value to change it to! Also, you can easily spot that the state of std::cin reflects if the previous read went past the end.
Since you are only checking the value of your integers without ensuring that they have a sane default (just check what happens to n if it is not set by reading the input), this can easily lead to your program exhibiting unexpected behavior.
Note: The behavior of the test program is different when fed input that simply is not a number.
When you supply cin with EOF it causes cin.failbit to become true. With the failbit set to true, all subsequent cin reads will be ignored. Since n has no default value execution becomes unpredictable from here. In my case the program was crashing because it was throwing 66. Adding cin.clear() after the while loop will fix this, but is not advisable. Two simple solutions would to stop on a magic number/prompt the user after every input if they want to continue.