How to extract the first digit of a 16 digit number? - c++

I have this code right here that compiles just fine getting the first digit of a 10 digit number.
I am wondering how to get my code to get the first digit of a 16 digit number?
I have tried changing 10 to 16 in the while loop and my program does not count the first digit. Here is my code down below:
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Enter a number : " << endl;
cin >> number;
// cout << "Last digit is : " << number % 10 << endl;
while(number >= 10)
{
number = number/10;
}
cout<< "First digit is : "<< number << endl;
return 0;
}

int has at least 16 bits. The exact size is implementation defined. Even with 32 bits the maximum value is 2147483647. You cannot store a 16 digit number in an int.
You can store numbers with more digits than any integer type can hold in a std::string. Because just reading some string from the user and printing the first character would be too much cheating, at least you should check that the user actually did enter a number:
#include <iostream>
#include <limits>
#include <cctype>
int main() {
std::cout << "max int : " << std::numeric_limits<int>::max() << "\n";
std::string number;
std::cin >> number;
for (const auto& c : number) {
if (std::isdigit(c) == 0) {
std::cout << c << " is not a valid digit !";
return 1;
}
}
if (number.size() > 0 && number[0] != '0') std::cout << number[0];
else std::cout << "invalid input";
}
Live Demo

Learning how to use <string> will prove very, VERY useful for you:
#include <iostream>
#include <string> //extremely useful
using namespace std;
int main()
{
string aux;
string number;
cout<<"Enter a number: "<<endl;
cin>>aux;
number=aux.substr(0,1); //create a substring of aux, starting from the first position (first argument) and getting only one character (second argument)
cout<<"First digit is "<<number<<endl;
return 0;
}
if you need the variable as int, use stoi():
int num=stoi(number);
if you want to be sure the input has 10 or 16 digits, use size():
int size=aux.size();
if (size!=10) //or 16, whatever you want
cout<<"invalid number"<<endl;

Changing 10 with 16 won't work at all, the problem is the upper limits of an int which is usually 2147483647, inputing values above this will not work, meaning the digit will always be 2.
What you need to do is to use a larger type. You can safely use long long int which can take 19 digits.
long long number;
It's max value is guaranteed to be 9223372036854775807 at least.
Ideally, if possible, you should extract the user input as a string, it would be a much easier task to then extract the first character as exemplified by largest_prime_is_463035818.

Related

Making 6 digit pins on array c++

I want to ask 6 digit pins from user, I tried this code, it does work. The problem is that it cannot read pin starting from 0. The objective of the code is to read 6 digit pin no matter what the start is, as long as it is an integer it will read the correct output.
using namespace std;
int main(){
int pin[0];
cin>>pin[0];
if (pin[0] >= 100000 && pin[0] <= 999999) {
cout << pin[0];
}
else {
cout << "Invalid input!";
}
}```
On the one hand you want to read an integer (you are comparing it to 100000 and 999999) on the other hand you want to read individual digits into an array. It cannot be both. And you cannot have an array of size 0.
Just stay with the single integer. If you want to access individual digits you can convert it to a string and access characters (you already made sure that it has 6 digits):
#include <iostream>
#include <string>
int main(){
int pin;
std::cin>>pin;
if (pin >= 100000 && pin <= 999999) {
std::cout << pin << "\n";
std::string pin_string = std::to_string(pin);
for (size_t i=0; i<6; ++i){
std::cout << pin_string[i] << "\n";
}
}
else {
std::cout << "Invalid input!";
}
}
Heres one way to do it.
Read CIN as std::string
Regex recv string for digit only
Confirm recv string len is == 6
Do w/e you want with it from there
Another way could be getChar()

Remove '0' from numbers less than and equal 9

How can I have an output of
Sample Input No.1:
9
Sample Output No.1:
1.2.3.4.5.6.7.8.9
If you input numbers less than or equal to 9, the output should be (1.2.3.4.5.6.7.8.9)
And if you input numbers greater than 9, for example:
Sample Input No.2:
20
Sample Output No.2:
01.02.03.04.05.06.07.08.09.10
11.12.13.14.15.16.17.18.19.20
My code below is for Sample Input & Output No.2. I tried adding another for loop for SAMPLE NO.1 but it still reads Sample No.2 code. What should I do?
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int a, num;
cin >> num;
if (num > 100 || num <= 1){
cout << "OUT OF RANGE";
}
else {
for (int a = 1; a < num; a++){
cout << setfill('0') << setw(2) << a << ".";
}
cout << num;
}
}
kind of new to programming, don't know much🥲
As a possible solution, you could read the input as a string, then convert it to an integer.
Use the string length as the field width for the setw manipulator.
This should be able to handle values of (theoretically) arbitrary length.

I wrote code to convert decimal fraction number to its binary equivalent. It compiles fine but when executed hangs

I wrote code to convert decimal fraction number to its binary equivalent. It compiles fine but when executed hangs. The code here prints only first four digits of the binary conversion and if the number if with more than 4 digits, it shows '...' after it. On execution it hangs. Help!
#include <iostream>
using namespace std;
int main()
{
int i, x[10];
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num>=0 && num<=1)
{
i=1;
while (num!=1.000)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
if (i>4)
{
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
cout << "...";
}
else
{
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
}
}
else
{
cout << "The number entered is out of range.";
}
return 0;
}
The first obstacle is the infinite while loop:
Assuming input num=0.5
after first iteration, i=1, x[0]=1, num=0.0
after second iteration, i=2, x[1]=0, num=0.0
Continue forever, i=..., x[i-]1=0, num=0.0
With nothing to break the loop.
while (num!=1.000)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
To fix, consider few changes. There might be other issues.
put a limit on the while loop (i<10 should be a good condition, as this is the size of the x array), or i=4, as this is the maximum output.
The break condition for the while loop should probably be 'num != 0', or even better (num > 1e-7, or other small value).
float has 23 bit in mantissa, maybe it is because you are assign x[i] with i greater than 9.
try this:
//stop when you get four bits
while (i< 5)
Original code has several issues:
1 For input num=.5 and similar (really for all values) cycle never ends (dash-o suggested fix ideas)
2 array x[10] is overflowed with undefined behavior (Edney)
3 nitpicking: 1 is not a “fraction” and better check for a range 0 <= num < 1 instead of 0 <= num <= 1(see also OP printing code; 1 could be added); we could use x[4] with 0<=i <=3
4 string could also be used (PaulMcKenzie). Really “>>” uses string processing for parsing and calculating binary equivalent from which by multiplying by 2 (left shit) and truncation fractional part the code calculates target bits. Both approaches give correct identical results; implementing by string we need to add internal to operator “>>” implementation code to parsing valid formats for floats (decimals) such as 3.14e-1, .2718, 1e-1, etc.
This fix follows OP:
#include <iostream>
using namespace std;
int main()
{
int i, x[5];
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num>=0 && num<1)
{
i=1;
while (i<=4)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
if (num>0)
cout << "...";
}
else
{
cout << "The number entered is out of range.";
}
return 0;
}
This code is without cycles (they are in code implementing “>>”, bitset):
#include <iostream>
#include <bitset>
using namespace std;
int main () {
const int digits = 4;
int fraction;
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num >= 0 && num < 1) {
fraction = num = num * pow (2, digits);
cout << "The binary equivalent is 0.";
cout << bitset<digits> (fraction);
if (num - fraction > 0) cout << "...";
}
else cout << "The number entered is out of range.";
}

Why is my C++ code wrong to calculate the maximum and minimum of integers?

I am learning the C++ programming language and I am a beginner. I had to write a code so that a user inputs a series of integers and whenever he enters -99, that should signal the end of the series and then my program needs to find the smallest and largest integers. I initially came up with this solution
#include <iostream>
using namespace std;
int main()
{
int k=0, number, maximum, minimum;
do
{
cout<<"Enter an integer: ";
cin>>number;
if (number==-99)
{
break;
}
if (k==0)
{
maximum=number;
minimum=number;
}
if (number>maximum)
{
maximum=number;
}
if (number<minimum)
{
minimum=number;
}
k++;
}
while(number!=-99);
cout<<"The smallest entered integer is "
<<minimum
<<" and the largest entered integer is "
<<maximum
<<endl;
return(0);
}
and sent it to my lecturer and asked if there is a cleaner way of doing this but he did not reply. Next, I changed this program to find the maximum and minimum using the formulas max(x,y)=(x+y+abs(y-x))/2 and min(x,y)=(x+y-abs(y-x))/2 instead using comparisons.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int k=0, number, maximum, minimum;
do
{
cout<<"Enter an integer: ";
cin>>number;
if (number==-99)
{
break;
}
if (k==0)
{
maximum=number;
minimum=number;
}
maximum=(maximum+number+abs(number-maximum))/2;
minimum=(minimum+number-abs(number-minimum))/2;
k++;
}
while(number!=-99);
cout<<"The smallest entered integer is "
<<minimum
<<" and the largest entered integer is "
<<maximum
<<endl;
return(0);
}
but this time my lecturer replied and the only thing he said was that it is wrong. I have tested both of my codes few times and they show me the correct result so I have no clue what my lecturer meant by saying it is wrong. Could someone please let me know why any of the two codes above is wrong and why?
Both of your programs work fine. If you'd like it be cleaner than you can do the following:
Check if the input succeeded before using number. You can do this by putting the input operation in a while loop.
Just use the max and min functions found in <cmath>.
This will be your program:
int main() {
int number = -100, maximum = -99, minimum = 99;
while (cin >> number && number != -99) {
maximum = max(maximum, number);
minimum = min(minimum, number);
}
if (number == -99) {
cout << "The smallest entered integer is " << minimum
<< " and the largest entered integer is " << maximum << endl;
}
}
There are several ways to correct the problem. One is to check for the value of k in your initial example to verify that a value was actually entered and that minimum and maximum are initialized.
A slightly different approach that might impress your lecturer is to initialize minimum and maximum to values that will lead to a correct result. std::numeric_limits provides the minimum and maximum values for integers. Using this you could implement something along these lines:
#include <iostream>
#include <limits>
#include <algorithm>
int main()
{
int number;
int maximum = std::numeric_limits<int>::min();
int minimum = std::numeric_limits<int>::max();
while ((std::cin >> number) && (number != -99))
{
maximum = std::max(maximum, number);
minimum = std::min(minimum, number);
}
if (std::cin)
{
if ((maximum != std::numeric_limits<int>::min()) || (minimum != std::numeric_limits<int>::max()))
{
std::cout << "maximum = " << maximum << std::endl;
std::cout << "minimum = " << minimum << std::endl;
}
else
{
std::cout << "No number entered" << std::endl;
}
}
else
{
std::cout << "Errorr reading the number" << std::endl;
}
}
The formulas used in your second code snippet are mathematically correct, but have drawbacks if used in computer programming where variables have limited range.
The first code snippet works across the entire representable set of integers (except -99 for obvious reasons).
The second code snippet will not work for inputs whose absolute value is greater than INT_MIN / -2, because the computations will overflow.
Don't feel bad, this bug is not at all obvious and a lot of programmers have overlooked it. For a related example, see:
Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken
Unfortunately, if you have this kind of bug in code processing untrusted input, your range checking could fail and lead to a security vulnerability. So don't go ignoring it just because "I never expect inputs that large".
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int number, maximum=0, minimum=0;
bool isDirty = false;
do
{
cout<<"Enter an integer: ";
cin>>number;
if(number!=-99){
if(isDirty==false) {
isDirty = true;
minimum = maximum =number;
} else {
if (number < minimum) {
minimum = number;
}
if (number > maximum){
maximum = number;
}
}
}
}
while(number!=-99);
cout<<"The smallest entered integer is "
<<minimum
<<" and the largest entered integer is "
<<maximum
<<endl;
return(0);
}

Boolean condition not working properly in do-while loop

The loop in the function require() takes 3 conditions, a > b or "a" or "b" aren't digits. Even when I don't satisfy the conditions and put 2 integers in, it just loops once again.
Also when I put in a character then it just endlessly loops "Enter minimum number Enter maximum number" ignoring the cins. Anyone know why? I'm a beginner so this is probably really obvious
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int random(int minN, int maxN) //generates random number within specified range
{
srand (time(NULL));
int x = (maxN - minN);
int y = minN + (rand() % (x+1));
return y;
}
int require() //makes sure a < b and both are digits
{
int a,b;
do {
cout << "Enter minimum number" << endl;
cin >> a;
cout << "Enter maximum number. Note: Has to be greater or equal to minimum." << endl;
cin >> b;
} while (a > b || !isdigit(a) || !isdigit(b));
return random(a,b);
}
int main()
{
cout << require() << endl;
}
You should not use isdigit as this relates to a particular character is a digiti. Instead the loop should look like this:
int require() //makes sure a < b and both are digits
{
validNumbers = true;
do
{
cout << "Enter minimum number" << endl;
cin.clear();
cin >> a;
} while (cin.fail());
do
{
cout << "Enter maximum number. Note: Has to be greater or equal to minimum."
<< endl;
cin.clear();
cin >> b;
} while (cin.fail() || a > b);
return random(a,b);
}
PS: You only need to call srand (time(NULL)); once at the start of the program.
You are reading the numbers as, well, numbers not as characters as the isdigit function expects. If you are using a C++11 compliant standard library, the values of a and b will actually be zero if the input is not valid integer numbers, which means that e.g. !isdigit(a) will be true. If you are using a non-C++11 library, then the value of a and b will be random, and will most likely cause !isdigit(a) to be true as well as the amount of valid digit ASCII values in a full 32-bit integer range is quite small.
If you read a reference about the input operator, like this one you will see that if extraction fails, then the streams failbit will be set. This can either be tested "inline" like this:
if (!(std::cin >> a))
{
std::cout << "Not a valid number, try again: ";
continue;
}
Or it can be tested using the streams fail function.