try& catch used to provide a value - try-catch

I used try and catch method in my program, but I did not procedure a value which user enter when an incorrect value is entered. For example user enter a string value and program says that please enter a number... then program do not allow that user enter a new value. What can I do? My codes are here. Thanks.
try
{
Console.Write("Please enter column number: ");
string str = Console.ReadLine();
int columno = int.Parse(str);
if (columno > 20)
{
Console.WriteLine("please enter a number between 1 and 20");
}
else
{
for (int j = 0; j < columno; j++)
{
Random rnd = new Random();
for (int i = 0; i < 6; i++)
{
int rndno = rnd.Next(1, 50);
Console.WriteLine(rndno);
}
}
}
}
catch
{
Console.WriteLine("please enter a number between 1 and 20", "Error");
}
Console.ReadLine();
}
}
}

I'm not sure for the language, probably C#, but it should be something like that:
Console.Write("Please enter column number: ");
int columno = 0;
while(true) {
try{
string str = Console.ReadLine();
columno = int.Parse(str);
if (columno < 21 && columno > 0) {
break;
}
}
catch {}
Console.WriteLine("please enter a number between 1 and 20", , "Error");
}
//Rest of the code
The problem is that you're catching the exception on your entire code instead of on input only, so you catch it and continue right after all the code. All the remaining part inside the try is not executed.

Related

if/else statements in for loop not working

I'm trying to make a program that asks for user input and the for loop should check if the input of both user id and pin matches any of the ten pre-made account's user id and pin, like an authorization system
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
struct account{
int uid;
int pin;
int user_bal;
};
int main()
{
int scan_uid, scan_pin;
int att = 3;
bool loop = true;
struct account user[10];
user[0].uid = 1234;
user[0].pin = 123456;
user[1].uid = 4181;
user[1].pin = 308592;
user[2].uid =1111;
user[2].pin =111111;
user[3].uid =2222;
user[3].pin =222222;
user[4].uid =4444;
user[4].pin =444444;
user[5].uid =5555;
user[5].pin =555555;
user[6].uid =6666;
user[6].pin =666666;
user[7].uid =7777;
user[7].pin =777777;
user[8].uid =8888;
user[8].pin =888888;
user[9].uid =9999;
user[9].pin =999999;
for (int i; i <= 9; i++){
user[i].user_bal = 1000;
}
do{
printf("\nEnter your user ID: ");
scanf("%d", &scan_uid);
printf("Enter your pin: ");
scanf("%d", &scan_pin);
printf("\n--------------------------------------------\n");
att--;
for (int i; i <= 9; ++i){
//printf("\n%d", i);
//printf("\n%d", user[i].uid);
//printf("\n%d", user[i].pin);
//printf("\n%d", scan_uid);
//printf("\n%d", scan_pin);
if (user[i].uid == scan_uid && user[i].pin == scan_pin){
loop = false;
}
else{
printf("\nThe username or password is incorrect!");
printf("\nYou have %d attempt(s) left.", att);
if (att > 0)
{
printf("\nPlease try again.\n");
}
else if (att == 0)
{
printf("\nUnauthorized Access.");
printf("\nReport for stolen credit card uploaded.");
}
}
}
}while (att > 0 || loop == false);
return 0;
}
I tried the relatively same code in python and it works perfectly there. I also checked if the "i" is correct and incremented and if it scanned the user input correctly. all ok. But i've hit a brick wall trying to solve why it just skips the 'if/else' and just scans input again.
I also tried an 'else if ' that does the opposite(!=) of the initial 'if' statement, with no luck.
Thanks.
Others have already pointed out that you need to initialize int i with int i = 0 in your for loop.
However, I would additionally like to point out several other mistakes here. First, your loop condition appears to be incorrect:
while (att > 0 || loop == false)
You want to continue the loop in the case where they haven't entered the correct value yet and where they still have more attempts left. However, as written, this will continue to loop even if the user enters the correct password. I think that this should actually be
while (att > 0 && loop == true)
Also, most languages don't require you to explicitly compare to true and false, so the following is stylistically better:
while (att > 0 && loop)
Also, as written, it prompts the user to try again; however, it doesn't prompt the user for input again after the first time, so it's impossible for the user to try again. You need to prompt the user for input again inside the loop if their input was incorrect.
A few issues ...
As Dan said, initialize i to 0. This will fix the segfault.
When you do loop = false; you need break; immediately afterwards.
And, your do/while condition is wrong. Change while (att > 0 || loop == false); into while ((att > 0) && loop);
The placement of the "incorrect passwords" related printf is incorrect. It should come after the for.
Otherwise, the same error message will be repeated 9 times for a single incorrect answer.
And, we want to exit the do/while loop [immediately after the for loop] if we see loop become false.
Here is the refactored code. It is annotated:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
struct account {
int uid;
int pin;
int user_bal;
};
int
main(void)
{
int scan_uid,
scan_pin;
int att = 3;
bool loop = true;
struct account user[10];
user[0].uid = 1234;
user[0].pin = 123456;
user[1].uid = 4181;
user[1].pin = 308592;
user[2].uid = 1111;
user[2].pin = 111111;
user[3].uid = 2222;
user[3].pin = 222222;
user[4].uid = 4444;
user[4].pin = 444444;
user[5].uid = 5555;
user[5].pin = 555555;
user[6].uid = 6666;
user[6].pin = 666666;
user[7].uid = 7777;
user[7].pin = 777777;
user[8].uid = 8888;
user[8].pin = 888888;
user[9].uid = 9999;
user[9].pin = 999999;
for (int i; i <= 9; i++) {
user[i].user_bal = 1000;
}
do {
printf("\nEnter your user ID: ");
scanf("%d", &scan_uid);
printf("Enter your pin: ");
scanf("%d", &scan_pin);
printf("\n--------------------------------------------\n");
att--;
// NOTE/BUG: i is uninitialized
#if 0
for (int i; i <= 9; ++i) {
#else
for (int i = 0; i <= 9; ++i) {
#endif
// printf("\n%d", i);
// printf("\n%d", user[i].uid);
// printf("\n%d", user[i].pin);
// printf("\n%d", scan_uid);
// printf("\n%d", scan_pin);
if (user[i].uid == scan_uid && user[i].pin == scan_pin) {
loop = false;
// NOTE/FIX: no need to continue loop if we get a match
#if 1
break;
#endif
}
}
#if 1
// stop if everything matched
if (! loop)
break;
#endif
printf("\nThe username or password is incorrect!");
printf("\nYou have %d attempt(s) left.", att);
if (att > 0) {
printf("\nPlease try again.\n");
}
else if (att == 0) {
printf("\nUnauthorized Access.");
printf("\nReport for stolen credit card uploaded.");
}
} while (att > 0);
return 0;
}
In the above code, I've used cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Note: this can be cleaned up by running the file through unifdef -k
First of all, you should initialize i to 0
To browse all array contents, you should increment i after the instruction NOT before (i++) instead of (++i)
Condition while loop is WRONG
Look at this version of your code, It works properly:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
struct account{
int uid;
int pin;
int user_bal;
};
int main()
{
int scan_uid, scan_pin;
int att = 3;
bool loop = true;
struct account user[10] = {0};
user[0].uid = 1234;
user[0].pin = 123456;
user[1].uid = 4181;
user[1].pin = 308592;
user[2].uid =1111;
user[2].pin =111111;
user[3].uid =2222;
user[3].pin =222222;
user[4].uid =4444;
user[4].pin =444444;
user[5].uid =5555;
user[5].pin =555555;
user[6].uid =6666;
user[6].pin =666666;
user[7].uid =7777;
user[7].pin =777777;
user[8].uid =8888;
user[8].pin =888888;
user[9].uid =9999;
user[9].pin =999999;
for (int i = 0; i <= 9; i++){
user[i].user_bal = 1000;
}
do{
printf("\n--------------------------------------------\n");
printf("\nEnter your user ID: ");
scanf("%d", &scan_uid);
printf("Enter your pin: ");
scanf("%d", &scan_pin);
printf("\n--------------------------------------------\n");
att--;
for (int i = 0; i <= 9; i++){
//printf("\n%d", i);
//printf("\n%d", user[i].uid);
//printf("\n%d", user[i].pin);
//printf("\n%d", scan_uid);
//printf("\n%d", scan_pin);
if (user[i].uid == scan_uid && user[i].pin == scan_pin)
{
loop = false;
break;
}
}
if (loop && att)
{
printf("\nThe username or password is incorrect!");
printf("\nYou have %d attempt(s) left.", att);
}
else if (! att && loop)
{
printf("\nUnauthorized Access.");
printf("\nReport for stolen credit card uploaded.\n");
}
else if (!loop)
{
printf("\nMatches !\n");
}
} while ((att > 0) && (loop == true));
return 0;
}

password verification or checker in c programming

I have created a password checker in c programming but it is not working can anyone please check it and say what is wrong in this.‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎‎
#include<stdio.h>
#include<stdbool.h>
int main() {
int otp[4]; //array for storing the true password entered by user at first
int pto[4]; //array for storing password for login
int count = 4,i;
bool pass = true;
printf("enter a new password: ");
for (int i = 0; i < count; i++) {
scanf("%d", & otp[i]); //for storing the true password
}
printf("\n\n --- Login page --- ");
printf("\nenter your password : ");
for (i = 0; i < count; i++) {
scanf(" %d", & pto[i]); //asking for password for login
}
for (i = 0; i < count; i++) { //check for password
if (otp[i] == pto[i]) {
pass = true;
} else {
pass = false;
}
}
while (pass == false) { //if password is wrong
printf("\n---- password din't match ----\nenter your password again : ");
for (i = 0; i < count; i++) {
scanf(" %d", & pto[i]);
}
for (i = 0; i < count; i++) {
if (otp[i] == pto[i]) {
pass = true;
} else {
pass = false;
}
}
}
printf("\n Your password is correct!");
return 0;
}
And should I use int or char to store passwords,if i use int also that part works if char also it works but sometimes it wont work,
This loop ultimately only cares if the last value in each array match or not.
for (i = 0; i < count; i++) {
if (otp[i] == pto[i]) {
pass = true;
} else {
pass = false;
}
}
For example, comparing { 1, 2, 3, 4 } and { 4, 4, 4, 4 } would result in pass being true after the loop, despite the obvious differences.
Instead, set the flag to false, and break from your loop as soon as a mismatch occurs.
bool matching = true;
for (size_t i = 0; i < length; i++) {
if (array_one[i] != array_two[i]) {
matching = false;
break;
}
}
If a mismatch never occurs, the flag will remain true afterwards.
Usually passwords are text that is hashed (with a salt) before being stored. Password verification is done by comparing hashes. For example, take a look at the man 3 crypt library function.
The use of a fixed-length series of plain integers for a 'password' is atypical, but for a toy program it is fine.
Here is an example program to study.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define KEY_LENGTH 4
void get_key(int *key, size_t length) {
for (size_t i = 0; i < length; i++) {
if (1 != scanf("%d", &key[i])) {
fprintf(stderr, "Could not read integer input.\n");
exit(EXIT_FAILURE);
}
}
}
bool match_key(int *one, int *two, size_t length) {
for (size_t i = 0; i < length; i++)
if (one[i] != two[i])
return false;
return true;
}
int main(void) {
int key[KEY_LENGTH];
int user_key[KEY_LENGTH];
printf("Set the key (%d integers): ", KEY_LENGTH);
get_key(key, KEY_LENGTH);
puts("--- LOGIN ---");
while (1) {
printf("Enter the key (%d integers): ", KEY_LENGTH);
get_key(user_key, KEY_LENGTH);
if (match_key(key, user_key, KEY_LENGTH))
break;
puts("Key mismatch. Retrying...");
}
puts("Welcome to the system.");
}
Since you didn’t specify your problem (besides “it’s not working”), I’ll do my best to list all the possible issues.
Reading integers
scanf("%d", & otp[i]);
Will read a single decimal integer into a position in otp. If the password is 1024, the first time through the loop (iteration) will read 1024 into otp[0]. In the second iteration, scanf() will wait until another number is available on standard input. Once it’s available, it will read it into otp[1], and so on. This scanf() loop really reads in 4 different integers, separated by newlines. It would be much easier to do only one scanf() for one integer, like this:
int main() {
int otp;
int pto;
bool pass = true;
printf("enter a new password: ");
scanf("%d", &otp);
You could also scan a 4-character string by using char arrays:
int main() {
char otp[5]; //4 digits and 1 NUL-terminator
char pto[5];
bool pass = true;
printf("enter a new password: ");
scanf("%4s", otp);
Password-checking logic error
As #Oka explained, your checker has a logic error. If using an integer, you could simply check
if (opt == pto) {
//correct
} else {
//incorrect
}
If using a char array (string), you could use
if (!strcmp(otp, pto)) {
//correct
} else {
//incorrect
}
You would have to #include <string.h> for strcmp().
Standard output buffer
The “enter a new password: ” prompt is not printed until the stdout buffer is flushed. This usually only happens when a newline is printed. You have to
fflush(stdout);
right after printing the prompt if you want it to appear.

How to make an array accept only numbers in c programming?

So my task is to make an array that accepts 10 characters. If the characters entered by the user are greater than 10, then an error is dispayed. If the 10 characters entered contain a letter, it displays another error.
Therefore, the array can only have 10 numbers and nothing else, if the numbers entered are less or more than 10, error is displayed as well as if there are letters in the array.
My code accepts both numbers and letters, as i cannot figure out how to display error when letters are entered.
void getTenDigitPhone(char telNum[])
{
int i;
int z = 1;
do
{
scanf("%s", telNum);
if (strlen(telNum) != 10)
{
printf("Enter a 10-digit phone number: ");
z = 1;
}
else if (strlen(telNum) == 10)
{
return telNum;
}
} while (z == 1);
}
You just need to check that telNum contains only digits:
for (int i = 0; i < 10; i++)
if (!isdigit(telNum[i])) {
// handle error because a non-digit was found.
}
I'm not going to do your homework for you but this should give you the idea.
You can use the function isdigit(x).
This returns true (non-zero) if x is a digit and returns false (zero) if not.
You have to check digit by digit.
I'm going to give an answer because you have posted your current code as your effort. As other answers you should use isdigit(x) function.
...
else if (strlen(telNum) == 10)
{
int i;
char err = 0;
for (i = 0; i < 10; i++) {
if (!isdigit(telNum[i])) {
// Your error here
printf("Non-digit character found");
err = 1;
break;
}
}
if (err == 0) {
return telNum;
}
}
...

I can not input the names into the char array using scanf

I can not use scanf to enter a name in stdnames array.
when compiled it had no error , but as soon as i enter a name and
then press enter to write the other name it gives an error and shuts the program.
How should I go about it ?
int main(int argc, char* argv[])
{
float marks[50];
/*char *stdnames[100]={"Arvind Thillainathan","Robert Lang"};*/
//I want to stores names like the above one
char *stdnames[100];
int totalNames = 0;
int i = 0, w=0,h=0;
printf("How many names do you want to enter ??\n");
scanf("%d",&totalNames);
assert(totalNames != 0);
for(int count = 0; count < totalNames; count++)
{
printf("Enter name of student\n");
scanf("%s",stdnames[count]);
//From here the problem starts
}
getres(marks,totalNames);
for(i = 0; i < totalNames; i++)
{
int v = 1;
printf("\n");
printf("IELTS Marks of %s\n\n",stdnames[i]);
for(h = w; h < w+5; h++)
{
if(v==1)
{
printf("Listening : %0.1f\n", marks[h]);
}
else if(v==2)
{
printf("Reading : %0.1f\n", marks[h]);
}
else if(v==3)
{
printf("Writing : %0.1f\n", marks[h]);
}
else if(v==4)
{
printf("Speaking : %0.1f\n", marks[h]);
}
else
{
printf("Overall : %0.1f\n\n", marks[h]);
}
v++;
//if(h==10)
//{
// break;
//}
}
w+=5;
}
return 0;
}
By
char *stdnames[100];
you got an array of (pointers to char).
The NEXT BIG QUESTION is
Who will allocate memory for each of these pointers?
A small answer would be - You have to do it yourself like below :
stdnames[count]=malloc(100*sizeof(char)); // You may replace 100 with desired size
or
stdnames[count]=malloc(100); // sizeof(char) is almost always 1
You need to put this line before the scanf statement.
Note: Don't forget to free the allocated memory once these variables become irrelevant. Do it like :
free(stdnames[count]);

Infinite loop on do while

I'm trying to do a simple method that ask for a number, but I'm having troubles with the condition, here is my code:
private static int rows(){
int w = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.println("What is the number of rows?");
if(sc.hasNextInt()) {
w = sc.nextInt();
if (w <= 0){
System.out.println("Error: the rows can't be 0 or negative number.");
}
}
else {
System.out.println("Error: please only use digits.");
}
}
while (w<=0);
return w;
}
So, when I introduce a negative number or zero the code works fine, but if I try to introduce a letter or a invalid character like a dot or comma, the program enter in a infinite loop repeating this:
System.out.println("What is the number of rows?");
System.out.println("Error: please only use digits.");
You are not refreshing w's value. Re-enable the use to enter a new value for w. Something like:
int w = 0;
Scanner sc = new Scanner(System.in);
do {
System.out.println("What is the number of rows?");
if(sc.hasNextInt()) {
w = sc.nextInt();
if (w <= 0){
System.out.println("Error: the rows can't be 0 or negative number.");
}
}
else {
System.out.println("Error: please only use digits.");
sc.next(); // Clear default input on invalid input
continue; // Restart the loop so it gets newer value again
}
}
while (w<=0);
return w;
w only gets changed in the case of sc.hasNextInt(). If you enter a letter / invalid character, w never gets changed, and your loop cannot end.

Resources