So I had a program that made a number out of entered digits, but it doesn't work. Here's what it should print:
Code:
This program creates a number one digit at a time.
Signal the end of the number with a negative value.
Enter a number: 4
Enter a number: 11
Enter a number: 5
Enter a number: 73
Enter a number: 6
Enter a number: 24
Enter a number: -1
You entered a 3 digit number: 456
but it doesn't work.
My code is:
Code:
/*
* Create a number by entering single digits similar to a calculator.
* If numbers other than 0 thru 9 are entered they should be ignored.
* At the end, display the number of digits and the final number.
*/
#include<iostream>
using namespace std;
int main()
{
// give instructions
cout << "This program creates a number one digit at a time." << endl;
cout << "Signal the end of the number with a negative value." << endl;
int number = 0;
int cin2 = 0;
int cinvar = 0;
// PUT CHECK FOR LEADING ZEROES (ZEROES BEFORE A NUMBER)
// begin reading digits until negative entered
int count = 0;
int digit = 0;
while (true) {
cout << "Enter a number: ";
cin >> digit;
if(digit != 0) {
cinvar++;
}
else {
cin2++;
}
if(cin2 < cinvar) {
if (digit < 0) {
break;
}
if (digit >= 0 && digit<=9) {
number = number + digit;
count++;
}
}
// count digits
// check to see if we are done
if (digit < 0) {
break;
}// add to our number
if (digit > 0 && digit<=9) {
number = number*10 + digit;
count++;
}
}
// final report
// count = count - 1;
cout << endl << "You entered a " << count << " digit number: " << number << endl;
}