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!";
}
}```
CodePudding user response:
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!";
}
}
CodePudding user response:
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()