Making 6 digit pins on array c++ - 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()

Related

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.

How to extract the first digit of a 16 digit number?

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.

from ascii to bits but not working the contrary

I got stuck in this problem.
I'm writing a c++ program in which:
1- you write a 6 chars string
2- that string is converted into bits (let's call this 'A')
3- this string of bits is copied in another string and reverted via reverse() method (let's call this 'B')
4- a bitwise OR is executed between A and B (let's call this result 'C')
5- (here's where i got stuck) C should be converted into ASCII.... but i'ts not. I get in output strange symbols/question marks.
Here's the code:
#include <iostream>
#include <bitset>
#include <sstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
// PART ONE: from string to bits
string input;
cout << "Insert the 6 letters string you want to convert: \n";
do
{
getline(cin, input);
if (input.length() < 6 || input.length() > 6)
{
cout << "\nIt must be 6 letters!\n";
}
} while (input.length() != 6);
string inbits;
bitset<8> newbits;
for (size_t i = 0; i < input.size(); ++i)
{
newbits = bitset<8>(input.c_str()[i]);
string aux = newbits.to_string<char, std::string::traits_type, std::string::allocator_type>();
inbits.append(aux);
}
cout << endl << inbits << endl;
// PART TWO: bitwise or
string inverted = inbits;
reverse(inverted.begin(), inverted.end());
bitset<48> bstr1(inbits), bstr2(inverted), finale;
finale = bstr1 | bstr2; // here it is done the bitwise OR
cout << finale << endl;
string ored = finale.to_string<char, std::string::traits_type, std::string::allocator_type>();
// PART THREE: from bits to string of char
stringstream sstream(ored);
string aux = "";
while (sstream.good())
{
bitset<8> bits;
sstream >> bits;
char c = char(bits.to_ulong());
aux += c;
}
cout << "the ored string is: " << aux << endl;
}
I don't know what goes wrong. I mean, it could be a sort of """overflow""" but
it just doesn't make any sense.
How should i proceed?
(Sorry for my bad english, this is the first time I open a thread here, I'm kind of unsure on how to move here)
If your results dont fall into the range 0x41 to 0x5A you wont get a alphabetical result:
Link to the ascii table site

Recognize "010" and similar numbers as a palindrome using modulus in C++

First post! This is my second semester with "Advanced C & C++" so any help is GREATLY appreciated. I've already scoured as much of stackoverflow and a few other resources to try and help me understand what I'm doing (or not doing) with this slew of logically inept code.
The goal of this program is to recognize whether or not a 'number' given by the user is a palindrome. Sounds simple enough right?! Ugh...well this is what I have been stuck on:
#include <iostream>
using std::cout;
using std::cin;
#include <string>
using std::string;
#include <cstdlib>
int main()
{
//variable declarations
string buffer;
//user input
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
//looooop
while(buffer != "Q" && buffer !="q")
{
int userNum, length, sum = 0, temp;
userNum = atoi(buffer.c_str());
for(temp = userNum; userNum !=0; userNum=userNum/10)
{
length = userNum % 10;
sum = sum*10+length;
}
if(temp==sum)
cout << temp << " is a palindrome!!\n\n";
else
cout << buffer << " is NOT a palindrome!\n\n";
cout << "Enter a number to see if it is a palindrome[Q to quit]: ";
getline(cin, buffer);
}
}
The problem arises when input of "010", or "400" is given. "400" is essentially "00400" in this case and both should be seen as a palindrome.
A better approach would be to get trailing zeros for the given number as below:
int noOfTrailingZeros = str.length;
while(str[--noOfTrailingZeros]=='0');
noOfTrailingZeros = str.length - noOfTrailingZeros;
Or the integer way as:
int noOfTrailingZeros = str.length;
while(num%10==0)
{
noOfTrailingZeros++;
num/=10;
}
Now, check for the input string whether it has the same number of zeros befire the number or not as:
int counterZeros = 0;
while(str[counterZeros++]=='0');
check these 2 numbers and if trailing zeros are more than the zeros at beginning, add that many at the beginning and pass that string to palindrome function.
First of all, to recognize a palindrome, you don't have to do atoi. Just pass from the start to the middle checking if
buffer[i] == buffer[length - i]
Second, use the atoi to make sure it is a number and you're done.
Other way is to compare the string with itself reversed:
string input;
cout << "Please enter a string: ";
cin >> input;
if (input == string(input.rbegin(), input.rend())) {
cout << input << " is a palindrome";
}

Integer input restricted to four digits only

I'm doing a problem where it asks to input an account number, which consists only of four digits. This has to be accomplished with basic beginner C++.
I need to figure out a way to restrict the input of the integer to four digits. A user should be able to put in 0043 or 9023 or 0001 and it should be an acceptable value....
I think I know how to accomplish it with a string.... getline(cin,input) and then check if input.length()==4?
But I've no idea how I would even do this with an integer input.
Note that if 0043 is intended to be distinct from 43, then the input is not in fact a number, but a digit string, just like a telephone "number".
Read the line as a string input.
Check that the length of input is 4.
Check that each character in the string is <= '9' and >= '0'.
Something like:
std::string read4DigitStringFromConsole()
{
bool ok = false;
std::string result;
while (!ok)
{
std::cin >> result;
if (result.length() == 4)
{
bool allDigits = true;
for(unsigned index = 0; index < 4; ++index)
{
allDigits = allDigits && (
(result[index] >= '0') &&
(result[index] <='9')
);
}
ok = allDigits;
}
}
return result;
}
Something like this should work. Once the user enters something with exactly four characters you can validate it. The rest of the logic is up to you.
#include <iostream>
#include <string>
int main() {
std::cout << "Enter a PIN Number: ";
std::string pinStr;
while(std::getline(std::cin,pinStr) && pinStr.size() != 4) {
std::cout << "Please enter a valid value\n";
}
}
Should you want to store it in an integer form, holding the integers in an std::vector might be beneficial. You can do this easily (loop unrolling was for clarity):
#include <iostream>
#include <string>
#include <vector>
int main() {
std::cout << "Enter a PIN Number: ";
std::string pinStr;
while(std::getline(std::cin,pinStr) && pinStr.size() != 4 ) {
std::cout << "Please enter a valid value\n";
}
std::vector<int> pin;
pin[0] = pinStr[0] - '0';
pin[1] = pinStr[1] - '0';
pin[2] = pinStr[2] - '0';
pin[3] = pinStr[3] - '0';
//pin now holds the integer value.
for(auto& i : pin)
std::cout << i << ' ';
}
You can see it running here
I like your idea to use a string as the input. This makes sense because an account "number" is simply an identifier. You don't use it in calculations. By if (sizeof(input)==4) I think you are trying to check the length of the string. The correct way to do this is if (input.length() == 4). This will check that the user inputs 4 characters. Now you need to make sure that each of the characters is also a digit. You can do this easily by taking advantage of the fact that the ASCII codes for digit characters are ordered as you expect. So if (input[i] >= '0' && input[i] <= '9') will do the trick with an appropriate for loop for the index i. Also, you probably need some kind of loop which continues to ask for input until the user enters something which is deemed to be correct.
Edit:
As an alternative to checking that each character is a digit, you can attempt to convert the string to an int with int value = atoi(input.c_str());. Then you can easily check if the int is a four-or-less-digit number.
// generic solution
int numDigits(int number)
{
int digits = 0;
if (number < 0) digits = 1; // remove this line if '-' counts as a digit
while (number) {
number /= 10;
digits++;
}
return digits;
}
similar to this post.
Then you can call this function to check if the input is 4 digits.
You probably want your code to be responsive to the user input, so I would suggest getting each character at a time instead of reading a string:
std::string fourDigits;
char currentDigit;
std::cout << "Enter 4 digits\n";
for(int i = 0; i < 4; ++i)
{
currentDigit = getch();
if(isdigit(currentDigit))
{
fourDigits += currentDigit;
std::cout << currentDigit; // getch won't display the input, if it was a PIN you could simply std::cout << "*";
}
else
{
// Here we reset the whole thing and let the user know he entered an invalid value
i = 0;
fourDigits = "";
std::cout << "Please enter only numeric values, enter 4 digits\n";
}
}
std::cout << "\nThe four digits: " << fourDigits.c_str();
This way you can handle gracefully invalid character instantly. When using strings, the input will only be validated once the user hits Enter.
So I was going over how I can use an integer type to get the input, and looked at char... since it's technically the smallest integer type, it can be used to get the code... I was able to come up with this, but it's definitely not refined yet (and I'm not sure if it can be):
int main() {
int count=0;
while(!(count==4)){
char digit;
cin.get(digit);
count++;
}
return 0;
}
So, the loop keeps going until 4 characters are collected. Well, in theory it should. But it doesn't work. It'll stop at 2 digits, 5 digits, etc.... I think it could be the nature of cin.get() grabbing white space, not sure.