I am trying to to print the last digits of a user inputted integer.
For example if the user inputs 5432
my output is
2
32
432
5432.
I have managed to write the code for this using a while loop, however i don't understand why my loop does not terminate, please help me terminate it?
void main()
{
//declare variables
int input, output, modulu = 10;
//read input from user
cout << "Please enter a number: ";
cin >> input;
int test = input % modulu; // test checks if all the number has been printed
//disect number
while (test > 0);
{
output = input % modulu;
modulu = modulu * 10;
cout << endl << output << endl;
test = input % modulu;
}
}
test is always > 0 for any input > 0
you can achieve the same with different loop:
int input, modulu = 1;
cout << "Please enter a number: ";
cin >> input;
do {
modulu *= 10;
cout << endl << (input % modulu) << endl;
} while ((input % modulu) != input);
Just
test = input / modulu;
instead of test = input % modulu;
For starters there is a semicolon after the while statement.
while (test > 0);
^^^
So the loop is infinite provided that the last digit of the entered number is not equal to 0.
However if you remove the semicolon the condition is invalid because test == 0 only in the case when the last digit is equal to 0.
Take into acount that main in C++ shall have return type int.
The program can look the following way
#include <iostream>
int main()
{
while ( true )
{
const unsigned int Base = 10;
std::cout << "Please enter a non-negative number (0-exit): ";
unsigned int x;
if ( !( std::cin >> x ) || x == 0 ) break;
unsigned int y = x;
unsigned int modulo = 1;
do
{
modulo *= Base;
std::cout << x % modulo << std::endl;
} while ( y /= Base );
std::cout << std::endl;
}
}
If for example to enter
123456789
0
then the output will look like
Please enter a non-negative number (0-exit): 123456789
9
89
789
6789
56789
456789
3456789
23456789
123456789
Please enter a non-negative number (0-exit): 0
Your first problem is here:
while (test > 0);
The ; terminates the while-statement and the code will stay in the while forever. In other words - all the code below is never executed. Remove the ;
Your second problem is the way you handle test - don't take modulo but divide by 10 instead. Like this:
int main()
{
//declare variables
int input, output, modulu = 10;
//read input from user
cout << "Please enter a number: ";
cin >> input;
int test = input; // <------------- Just make test equal to the input
while (test > 0) // <------------- The ; removed
{
output = input % modulu;
modulu = modulu * 10;
cout << endl << output << endl;
test = test / 10; // <----------- Divide by 10
}
return 0;
}
Notice that the above code has some problems with zeros, e.g. 1001 will output 1 1 1 1001 instead of 1 01 001 1001.
You can fix that by a completely different approach using stringinstead of int
Like:
int main()
{
//declare variables
string input;
//read input from user
cout << "Please enter a number: ";
cin >> input;
cout << input << endl;
int size = input.size();
int tmp = size;
while (tmp >= 0)
{
for (int t = tmp; t < size; t ++) cout << input[t];
cout << endl;
--tmp;
}
return 0;
}
Related
I'm trying to write a program that reads in positive float numbers from the user and then when the user's is a negative number, gives the average of the numbers, excluding the negative.
#include <iostream>
using namespace std;
int main() {
float av_number, total = 0, input;
do {
for (int i = 1; i >= 1; i = ++i) {
cout << "Please input a number: ";
cin >> input;
total = total += input;
av_number = total / i;
cout << av_number << endl;
break;
}
} while (input >= 0);
cout << av_number << endl;
}
When I run this, the program simply adds the inputs together on each line, and then subtracts my final negative input before closing the program.
If I were to guess, It's likely a logical confliction within my sequence of do & for loops, but I'm unable to identify the issue. I may have also misused i in some fashion, but I'm not certain precisely how.
Any help would be appreciated as I'm still learning, Cheers!
you don't need the for loop, you just need some iterator to count the number of entered numbers, so you can delete that for loop and use a counter variable instead.
also, you are breaking in the loop without checking if the input < 0, so you can write this
if (input < 0)
break;
also, you shouldn't calculate av_number = total / counter; except only after the end of the big while loop
it's total += input; not total = total += input;
writing while (input >= 0) wouldn't make sense as long as you are breaking inside the loop when input < 0, so you can write while (true); instead
and this is the code edited:
#include <iostream>
using namespace std;
int main() {
float av_number = 1.0, total = 1, input = 1.0;
int counter = 0;
do {
cout << "Please input a number: ";
cin >> input;
if (input < 0)
break;
counter++;
total += input;
} while (true);
av_number = total / counter;
cout << av_number << endl;
}
and this is the output:
Please input a number: 5
Please input a number: 12
Please input a number: 7
Please input a number: -2
8
P.S : read more about Why is "using namespace std;" considered bad practice?
You should move the calculation of the average value out of the loop where the adding takes place and only add non-negative values to total.
#include <iostream>
int main() {
float total = 0.f;
int i = 0;
// loop for as long as the user successfully enters a non-negative value:
for (float input; std::cout << "Please input a number: " &&
std::cin >> input &&
!(input < 0.f); ++i)
{
// now `input` is non-negative
total += input; // and only sum it up here, no average calculation
}
if (i > 0) { // avoid division by zero
// finally calculate the average:
float av_number = total / i;
std::cout << av_number << '\n';
}
}
The condition for the loop is that std::cout << "Please input a number: " succeeds and that std::cin >> input succeeds and that input is not less than zero.
I am coding a program that converts a binary number into decimal number by doubling (link to wikihow article).
If the user input is something other than 1 or 0, then its not a binary number, under that circumstance I want the loop to "break" and say something like:
"Oops! Binary numbers have only 1 or 0".
If not "then" the loop should continue.
That is I want to code something like
for(int digits = 0; digits != digitsINbinNum; ++digits){
if(a condition that checks if user input is anything else than 1 or 0){
coût << ""Oops! Binary numbers have only 1 or 0" << endl;
break;
}else{
cin >> binArray[digits];/*<-----------Here's the part where I am trying to do that*/
}
}
Refer to the code given below for more info:
#include <iostream>
#include <iterator>
using namespace std;
int main(){
int digitsINbinNum;
cout << "If you don't mind. Please enter the number of digits in your binary number: ";
cin >> digitsINbinNum;
int binArray[digitsINbinNum];
cout << "Enter the binary number: ";
for(int digits = 0; digits != digitsINbinNum; ++digits){
cin >> binArray[digits];/*<-----------Here's the part where I am trying to do that*/
}
/*using the doubling method as found in wikihow.com*/
int total = 0;
for(int posiOFdigit = 0; posiOFdigit != sizeof(binNum[noOFdigits]); posiOFdigit++){
total = total * 2 + binNum[posiOFdigit];
}
/*Printing the number*/
cout << "Decimal form of ";
for(int n = 0; n != noOFdigits; n++){
cout << binNum[n];
}
cout << " is " << total;
return 0;
}
The logic for converting a binary number into decimal number by the doubling method can be referred from the given link in the question.
Modifying the given code to keep it as close as possible to the question's reference code.
Note: As ISO C++ forbids variable length array, I am changing
int binArray[digits] to
int *binArray = (int *)malloc(sizeof(int) * digitsINbinNum);.
This modification makes it an integer pointer and it gets the memory of required size allocated at runtime.
#include <iostream>
using namespace std;
int main(){
int digitsINbinNum,
/* variable to keep decimal conversion of given binary */
decimal_val = 0;
bool is_binary = true;
cout << "If you don't mind. Please enter the number of digits in your binary number: ";
cin >> digitsINbinNum;
/*
ISO C++ forbids variable length array,
making it int pointer and allocating dynamic memory
*/
int *binArray = (int *)malloc(sizeof(int) * digitsINbinNum);
if (binArray == NULL)
{
cout << "Memory allocation failure" << endl;
exit -1;
}
cout << "Enter the binary number: ";
for(int digits = 0; digits != digitsINbinNum; ++digits){
cin >> binArray[digits];
/*<-----------Here's the part where I am trying to do that*/
/* doubling method logic for conversion of given binary to decimal */
if ((binArray[digits] == 0) ||
(binArray[digits] == 1))
{
decimal_val = (decimal_val * 2) + binArray[digits];
}
else /* not a binary number */
{
is_binary = false;
cout << "Oops! Binary numbers have only 1 or 0" << endl;
break;
}
}
/* if conversion is successful: print result */
if (is_binary)
{
cout << "Decimal Value for given binary is: " << decimal_val << endl;
}
if (binArray)
{
free(binArray);
}
return 0;
}
You don't need an array for this. Here is a simple solution:
#include <iostream>
int main(){
int digitsINbinNum;
std::cout << "If you don't mind. Please enter the number of digits in your binary number: ";
std::cin >> digitsINbinNum;
std::cout << "Enter the binary number: ";
int ret = 0;
for(int digits = 0; digits != digitsINbinNum; ++digits) {
int bin;
std::cin >> bin;
if (bin == 1 || bin == 0) {
ret = 2 * ret + bin;
} else {
std::cout << "Oops! Binary numbers have only 1 or 0" << std::endl;
return -1;
}
}
std::cout << ret << std::endl;
return 0;
}
I just started learning c++ and is learning topics related to cin, cin.get. In one of my assignments, the requirement is this:
Write a program that reads in a list of integer numbers and prints the largest and the
smallest number.
You can assume that the the user's input is always valid.
You can assume that the numbers in the list are separated by one space character and
that the character following the last number in the list is the newline character .
Implement a loop in which the above actions are repeated until the user requests to quit.
The code I came up with is:
using namespace std;
int main()
{
char ch = ' ';
int max=0;
do
{
int x;
cin >> x;
ch = cin.get();
if (max = 0) { max = x; };
if (x > max) { max = x; };
} while (ch != '\n');
cout << "maximum=" << max << endl;
return 0;
}
I was expecting to have this return the maximum of the numbers in the list. But it turned out only to return the last integer in the list.
I also don't quite get why the line:
cin >> x;
ch = cin.get();
makes the program able to accept a list of numbers. Isn't cin suppose to ask the user to input some stuff, as well as cin.get? In another word, shouldn't the user encounter input two times? But why is it when I run I am only asked to input once?
After some adjustment using the comments in this post, I was able to come up with the code as such:
int main()
{
cout << "Enter the list of integer numbers: ";
char ch = ' ';
int max=0;
int min = 0;
do
{
int x;
cin >> x;
ch = cin.get();
if (max == 0) { max = x; };
if (x > max) { max = x; };
if (min == 0) { min = x; };
if (x < min) { min = x; };
} while (ch != '\n');
cout << "maximum=" << max << endl;
cout << "minimum=" << min << endl;
return 0;
My final question is: How can I satisfy the requirement of this assignment "Implement a loop in which the above actions are repeated until the user requests to quit."
Your initial problem lies with the code:
if (max = 0) { max = x; };
The single = is assignment, not comparison. What is does is set max to zero, then use that zero as a truth value, which always equates to false.
Hence the effect is that max will be set to zero, and the body of the if will never be executed.
You need to use == for comparison.
In terms of looping until user indicates they want to quit, you can use the fact that invalid input can be detected with the >> extraction operator.
As an aside, since extraction of an integer first skips white-space, you don't have to worry about handling spaces and newlines at all, they'll naturally be skipped as part of the "get next integer" operation.
By way of example, the following complete program will exit when you enter q (or any invalid number for that matter, though if you enter 47q, it will handle the 47 first before exiting on the q):
#include <iostream>
int main () {
int inVal;
while (true) {
std::cout << "Enter number (q to quit): ";
if (! (std::cin >> inVal)) break;
std::cout << inVal << '\n';
}
std::cout << "Done\n";
}
A sample run follows:
Enter number (q to quit): 1
1
Enter number (q to quit): 2
2
Enter number (q to quit): 3
3
Enter number (q to quit): 55
55
Enter number (q to quit): 42
42
Enter number (q to quit): q
Done
So you can use that to detect non-numeric input and act accordingly:
#include <iostream>
int main () {
int inVal, maxVal, minVal, firstTime = true;
while (true) {
std::cout << "Enter number (q to quit): ";
if (! (std::cin >> inVal)) break;
if (firstTime) {
firstTime = false;
minVal = maxVal = inVal;
} else {
if (inVal > maxVal) {
maxVal = inVal;
}
if (inVal < minVal) {
minVal = inVal;
}
}
}
if (firstTime) {
std::cout << "*** You didn't enter any numbers.\n";
} else {
std::cout << "*** Minimum was " << minVal
<< ", maximum was " << maxVal << ".\n";
}
}
Some sample runs of that:
pax:~> ./testprog
Enter number (q to quit): q
*** You didn't enter any numbers.
pax:~> ./testprog
Enter number (q to quit): 1
Enter number (q to quit): q
*** Minimum was 1, maximum was 1.
pax:~> ./testprog
Enter number (q to quit): 9
Enter number (q to quit): 8
Enter number (q to quit): -3
Enter number (q to quit): 7
Enter number (q to quit): 5
Enter number (q to quit): 42
Enter number (q to quit): q
*** Minimum was -3, maximum was 42.
I'm assuming here the allowed assumption that the user input is always valid applies to the allowed characters being input (such as "no 47q allowed"), and that, if the marker complains that you're meant to stop on the first newline, you can argue that any number after that newline constitutes invalid data, and is therefore an invalid test case.
In the real world, you'd write your code robustly enough to handle edge cases like that but I suspect it's not necessary for educational work (even if it may earn you some extra marks).
I've been working on a program that calculates the mean of the user's inputs. I couldn't figure out yet, what to use for the input checker. I can't use arrays or strings yet. How do I check that both inputs are numerical values? And if they are not; how do I ask again for the correct input?
#include <iostream>
using namespace std;
int main()
{
// Get number from user
int input = 0;
double accumulator = 0;
double mean;
cout << "How many numbers would you like me to average together?\n";
cin >> input;
if (input >= 0){ //to check if input is a numerical value
// Compute and print the mean of the user input
int number = 1;
double x;
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
if (x < 0 || x > 0){ //to check if x is a numerical value
accumulator = accumulator + x;
}
else {
cout << "Input incorrect"<< endl;
}
number = number + 1;
}
mean = accumulator / input; // formula corrected
cout << "The mean of all the input values is: " << mean << endl;
cout << "The amount of numbers for the average calculation is: " << input << endl;
}
else {
cout << "Input incorrect"<< endl;
}
return 0;
}
You can use cin.fail to check for errors. Note that if user inputs a number followed by letters, lets say 123abc, then x will be stored as 123 but abc remains in the input buffer. You may wish to clear that right away so abc doesn't appear in the next loop.
while (number <= input) //while corrected
{
cout << "Please type a numerical value now: \n";
cin >> x;
bool error = cin.fail();
cin.clear();
cin.ignore(0xFFFF, '\n');
if (error)
{
cout << "Input incorrect" << endl;
continue;
}
accumulator = accumulator + x;
number = number + 1;
}
Alternatively you can initialize x. For example
double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');
if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}
If error occurs then x remains unchanged and you know there was an error, because it is unlikely that the user inputs a number matching numeric_limits<double>::min()
Not related to this issue, but you should also account for divide by zero error.
if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
int number=0;
cout<<"enter an number to cumpute";
cin>>number;
if(number=0)
cout<<"0"<<endl;
for(number>0;51>number;) {
number--;
cout<<"=";
}
for(number>10;number%10==0;) {
cout<<"|";
}
for(number>5;number%5==0;) {
cout<<"+";
}
cout<<endl;
system("PAUSE");
return 0;
}
(i got textbook called by Y.Daniel Liang. I can not find any thing like this) I have no idea how to make this loop work and I try use "while" and not working either. Should i just cout the "=" "+" "|", or start as string. I hope the output look like this.
BarPlot – A Simple Bar Graph Plotter:
Input a number in range [0 50] or a negative number to terminate:
| Enter Number: 6
| ====+> 6
| Enter Number: 12
| ====+====|=> 12
| Enter Number: 50
| ====+====|====+====|====+====|====+====|====+====> 50
| Enter Number: 53
| ERROR: 53 is not in acceptable range.
| Enter Number: 33
| ====+====|====+====|====+====|==> 33
| Enter Number: 0
| 0
| Enter Number: 5
| ====> 5
| Enter Number: -1
------------------------------------------------
BarPlot – End Plot by User Request
There is no need for you to convert a number to a string in order to solve the problem. The object cout can handle printing both numbers and strings without you needing to cast between them.
//example
int number = 1;
string str = "hello;
char c = '!';
//print hello1!
cout << str << number << c;
Here is a solution to the problem that does not require the need to cast an integer to a string.
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
//output inital prompt
cout << "BarPlot – A Simple Bar Graph Plotter:\n";
cout << "Input a number in range [0 50] or a negative number to terminate.\n\n";
//read in input
int number = 0;
cout << "Enter Number: ";
cin >> number;
//continue asking for input until a negative number is given
while (number >= 0){
for (int i = 1; i < number; ++i){
//special symbol every 10th char
if (i % 10 == 0) cout << "|";
//special symbol every 5th char
else if (i % 5 == 0) cout << "+";
//every other char
else cout << "=";
}
//print 0 or the number with an arrow before it
if (number == 0) cout << 0;
else cout << "> " << number << "\n";
//re-ask for input
cout << "\nEnter Number: ";
cin >> number;
}
//output ending message
cout << "BarPlot – End Plot by User Request\n";
return EXIT_SUCCESS;
}