'can c++ using cin to read one digit like scanf
does c++ have similar measure like scanf("%1d)
read only one digit in cin >>
or only #include <cstdin>
and use scanf
I try to use setw() but it seem to use in string
Solution 1:[1]
Here, take a look at this method
#include <iostream>
int main(){
std::cout << "Enter a number : ";
std::string input;
std::getline(std::cin, input);
int num = input[0] - 48; // converting char to int by ASCII values
// int num = input[0] - '0'; can also be used
cout << num;
return 0;
}
Even if many digits are entered as input, the program only accepts the first digit.
Solution 2:[2]
A digit is nothing else than a single character.
In order to read a single character from std::cin
, you can use operator>>
, or you can use std::istream::get
.
Using operator>>
:
char digit;
std::cin >> digit;
Using std::istream::get
:
char digit;
std::cin.get( &digit );
In order to convert char digit
to an integer, assuming that digit
is in the range '0'
to '9'
, you can write the following:
int number = digit - '0';
You can do this because the ISO C++ standard guarantees that the characters '0'
to '9'
are stored consecutively in the character set. For example, in ASCII, the characters '0'
to '9'
have the character codes 48
to 57
. Therefore, if you simply substract 48
(which is the character code for '0'
) from the character code, you will get a result between 0
and 9
, which is the value of the digit.
Here is an example program:
#include <iostream>
#include <cstdlib>
int main()
{
int number;
char digit;
//prompt user for input
std::cout << "Please enter a digit: ";
//attempt to read a single character
std::cin >> digit;
//verify that no input error occurred
if ( !std::cin )
{
printf( "Input error!\n" );
std::exit( EXIT_FAILURE );
}
//verify that character is in the range '0' to '9'
if ( ! ( '0' <= digit && digit <= '9' ) )
{
printf( "Character is not a digit!\n" );
std::exit( EXIT_FAILURE );
}
//convert digit to integer
number = digit - '0';
//print result
std::cout <<
"The digit was successfully converted to " << number << ".\n";
}
This program has the following behavior:
Please enter a digit: 7
The digit was successfully converted to 7.
It only accepts digits:
Please enter a digit: a
Character is not a digit!
It will only read the first digit, not a whole number:
Please enter a digit: 38
The digit was successfully converted to 3.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |