Friday, 6 January 2017

Operators such as >>, which read input from the keyboard, must be able to convert a series of digits into a number. Write a program that does the same thing. It should allow the user to type up to six digits, and then display the resulting number as a type long integer. The digits should be read individually, as characters, using getche(). Constructing the number involves multiplying the existing value by 10 and then adding the new digit. (Hint: Subtract 48 or ‘0’ to go from ASCII to a numerical digit.) Here’s some sample interaction: Enter a number: 123456 Number is: 123456

Leave a Comment
Object-Oriented Programming in C++ Fourth Edition By Robert Lafore Chapter-3 C++ Loops and Decisions  -- Questions+Exercises

Question:

Operators such as >>, which read input from the keyboard, must be able to convert a series of digits into a number. Write a program that does the same thing. It should allow the user to type up to six digits, and then display the resulting number as a type long integer. The digits should be read individually, as characters, using getche(). Constructing the number involves multiplying the existing value by 10 and then adding the new digit. (Hint: Subtract 48 or ‘0’ to go from ASCII to a numerical digit.) Here’s some sample interaction:

Enter a number: 123456
Number is: 123456

Explanation:
Below mention code is compiled in Visual Studio 2015 and Code Blocks 13.12,output snap is attached.. If any problem you feel and you want some explanation feel free to contact us.

Code:

/**************************************************|
/*************C++ Programs And Projects************|
***************************************************/
// makes a number out of digits
#include <iostream>
using namespace std;
#include <conio.h>                   //for getche()
int main()
{
       char ch;
       unsigned long total = 0;          //this holds the number
       cout << "\nEnter a number : ";
       while ((ch = _getche()) != '\r')    //quit on Enter
              total = total * 10 + ch - '0';     //add digit to total*10
       cout << "\nNumber is : " << total << endl;
       return 0;

}

Output:
Operators such as >>, which read input from the keyboard, must be able to convert a series of digits into a number. Write a program that does the same thing. It should allow the user to type up to six digits, and then display the resulting number as a type long integer. The digits should be read individually, as characters, using getche(). Constructing the number involves multiplying the existing value by 10 and then adding the new digit. (Hint: Subtract 48 or ‘0’ to go from ASCII to a numerical digit.) Here’s some sample interaction:  Enter a number: 123456 Number is: 123456



Related Articles:



If You Enjoyed This, Take 5 Seconds To Share It