I have got an assignment from uni which mentions that I have to compare a given set of passwords to the password given by the user. The set of passwords are predetermined in the question as follows
const char *passwd[NUM_PASSWDS] = {
"123foo", "bar456", "bla_blubb"
};
and has to be compared with input from user...
So I have written my code as follows;
#include <stdio.h>
#include <string.h>
#define NUM_PASSWDS 3
const char *passwd[NUM_PASSWDS] = {
"123foo", "bar456", "bla_blubb"
};
int pwdquery(char pass[]) {
for (int i = 0; i < 2; i++) {
if (passwd[i] == pass[i]) {
return printf("correct");
}
}
}
int main() {
char a[100];
for (int i = 0; i < 3; i++) {
printf("Please enter password");
scanf("%s", a);
}
pwdquery(a);
}
When I tried running my code, it shows an error...
Thank you for your time
To compare string you need to strcmp function.
printf returns number of character printed. You should return fixed value on success or failure of password match. In my example I'm returning 1 in case of password match or 0 in case of no-password match.
In main function scanf function with %s argument can read entire string. You don't need for-loop to read input string.
#include<stdio.h>
#include<string.h>
#define NUM_PASSWDS 3
const char* passwd[NUM_PASSWDS] = {
"123foo", "bar456", "bla_blubb"
};
int pwdquery(char pass[]) {
for (int i = 0; i < NUM_PASSWDS; i++)
{
if (strcmp(pass, passwd[i]) == 0)
{
return 1; // One means currect password
}
}
return 0; // Zero means incorrect password password
}
int main() {
char a[100];
printf("Please enter password");
scanf("%s", a);
if(pwdquery(a) == 1)
{
printf("Password entered is correct");
}
else
{
printf("Password entered is incorrect");
}
}
With custom strcmp
#include<stdio.h>
#include<string.h>
#define NUM_PASSWDS 3
const char* passwd[NUM_PASSWDS] = {
"123foo", "bar456", "bla_blubb"
};
//Returns 0 if string don't match else returns 1
int user_strcmp(const char *str1, const char *str2)
{
size_t str1_size = strlen(str1);
size_t str2_size = strlen(str2);
if(str1_size != str2_size)
{
return 0; //String are not of same size. The strings won't match.
}
for(size_t i = 0; i < str1_size; i++)
{
if(str1[i] != str2[i])
{
return 0;
}
}
return 1;
}
int pwdquery(char pass[]) {
for (int i = 0; i < NUM_PASSWDS; i++)
{
if (user_strcmp(pass, passwd[i]) == 1)
{
return 1; // One means currect password
}
}
return 0; // Zero means incorrect password password
}
int main() {
char a[100];
printf("Please enter password");
scanf("%99s", a);
if(pwdquery(a) == 1)
{
printf("Password entered is correct");
}
else
{
printf("Password entered is incorrect");
}
}
There are multiple problems in your code:
the password comparison function pwdquery compares a character and a pointer: this is incorrect. You should use strcmp to compare the strings and return a non zero value if one of these comparisons returns 0.
in the loop, you ask for the password 3 times, but you only check the password after this loop, hence only test the last one entered.
scanf("%s", a) may cause a buffer overflow if the user enters more than 99 characters without white space. Use scanf("%99s", a) to tell scanf the maximum number of characters to store into a before the null terminator.
Here is a modified version:
#include <stdio.h>
#include <string.h>
#define NUM_PASSWDS 3
const char *passwd[NUM_PASSWDS] = {
"123foo", "bar456", "bla_blubb",
};
int pwd_check(const char *pass) {
for (size_t i = 0; i < NUM_PASSWDS; i++) {
if (passwd[i] && strcmp(passwd[i], pass) == 0)
return 1;
}
return 0;
}
int main() {
char a[100];
for (int i = 0; i < 3; i++) {
printf("Please enter password: ");
if (scanf("%99s", a) != 1) {
printf("missing input, aborting\n");
return 1;
}
if (pwd_check(a)) {
printf("correct!\n");
return 0;
}
printf("incorrect password\n");
}
printf("too many errors, aborting\n");
return 1;
}
Related
If the user inputs a value that matches with an int in the array continue the program else quit the program.
My issue is that the function loops the whole array and if it finds one of the values doesnt match it will quit.
//Check if the user input matches with one of the ints in the array
void check(int num, int arr[]) {
for (int i = 0; i < 3; i++) {
if (arr[i] != num) {
printf("Invalid input");
exit(0);
}
}
}
void main() {
int arr[3] = { 1, 2, 3 };
int num = 0;
for (int i = 0; i < 3; i++) {
printf("%d ", arr[i]);
}
printf("\nPLease enter a value which matches with the array %d", num);
scanf("%d", &num);
check(num, arr);
}
void check(int num, int arr[]) {
for (int i = 0; i < 3; i++) {
if (arr[i] == num) {
return;
}
}
printf("Invalid input");
exit(0);
}
Your issue is that checks a single element and judges the input on that specific value. If it has run through each value and the function has still not returned, there is not match and we can exit the program.
You have a logic flaw in the check function: you should output the message and quit if none of the values match the input. You instead do this if one of the values does not match. The check always fails.
Here is a modified version:
#include <stdio.h>
//Check if the user input matches with one of the ints in the array
void check(int num, const int arr[], size_t len) {
for (size_t i = 0; i < len; i++) {
if (arr[i] == num) {
// value found, just return to the caller
return;
}
}
// if we get here, none of the values in the array match num
printf("Invalid input: %d\n", num);
exit(1);
}
int main() {
int arr[3] = { 1, 2, 3 };
size_t len = sizeof(arr) / sizeof(*arr); // length of the array
int num;
for (size_t i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
printf("Please enter a value which matches with the array: ");
if (scanf("%d", &num) == 1) {
check(num, arr, len);
} else {
// input missing or not a number
printf("Invalid input\n");
}
return 0;
}
You are right, you do exit once arr[i] != num (When the value is not the same as the i:th element in the array).
So, you could change it to: arr[i] == num. If it is the same, perhaps print "You got it!", and a return afterwards.
Starting to learn C. The main function is executing fine, but the program finishes running without ever executing the second function. I feel like I'm making a mistake here in the for loop in main.
int check_key_length(int count);
int main(void)
{
char key[20];
int count = 0;
printf("Enter key: ");
scanf("%s", key);
for(int i = 0; i < strlen(key); i++)
{
if (key[i] != ' ')
count++;
}
printf("Total number of characters in a string: %d", count);
}
int check_key_length(int count)
{
int set_amount = 26;
if (count < set_amount)
printf("Error: Your key is too short! Please input 26 chars\n");
else if (count > set_amount)
printf("Error: Your key is too long! Please input 26 chars\n");
else
string message = get_string("Enter string to encrypt: ");
return 0;
}
You forward declared your function, provided a definition for it, but you need to call the function in your main for your machine to execute it, something like this calls your function as expected
#include <stdio.h>
#include <string.h>
int check_key_length(int count);
int main(void)
{
char key[27];
int count = 0;
int strLength;
do {
printf("Enter key: ");
scanf("%s", key);
strLength = strlen(key);
} while(check_key_length(strLength) != 0);
for(int i = 0; i < strLength; i++)
{
if (key[i] != ' ')
{
count++;
}
}
printf("Total number of characters in a string: %d\n", count);
return 0;
}
int check_key_length(int count)
{
int set_amount = 26;
if (count < set_amount)
{
printf("Error: Your key is too short! Please input 26 chars\n");
return -1;
}
else if (count > set_amount)
{
printf("Error: Your key is too long! Please input 26 chars\n");
return -2;
}
else
{
return 0;
}
}
Note I had to modify the code a bit for it to build without any warning or error, I probably changed the behavior in a way you're not expecting so check my code before pasting it in
Hi I am currently having a problem with my program. When i enter a phone number char, and compare it with a different phone number char, the answer comes back false.
Here my function searches the "findContact" function for a exact number. The getTenDigitPhone is the function to get the phone number.
I end up getting the * Contact NOT FOUND * regardless if it matches or not
void searchContacts(const struct Contact contact[], int size) {
char phone[11];
int searchIndexContact;
printf("Enter the cell number for the contact: ");
getTenDigitPhone(phone);
searchIndexContact = findContactIndex(contact, size, phone);
if (searchIndexContact > -1) {
printf("\n");
printf("Contact found:\n");
displayContact(&contact[searchIndexContact]);
}
else {
printf("*** Contact NOT FOUND ***\n");
}
}
** Here is the getTenDigitPhone function
void getTenDigitPhone(char telNum[11])
{
int needInput = 1;
while (needInput == 1) {
scanf("%10s", telNum);
clearKeyboard();
// (String Length Function: validate entry of 10 characters)
if (strlen(telNum) == 10)
needInput = 0;
else
printf("Enter a 10-digit phone number: ");
}
}
And here is the findContactIndex (to find out if the numbers match)
int findContactIndex(const struct Contact contacts[], int size, const char cellNum[])
{
int i;
int value = 0;
for (i = 0; i < size; i++) {
if (contacts[i].numbers.cell == cellNum);{
printf(" %s %s",contacts[i].numbers.cell , cellNum);
value == 1;
}
}
if (value == 1) {
return value;
}
if (value == 0) {
return -1;
}
}
Enable your compiler's warnings! It would have found your problems. For example, with gcc, use at least
gcc -Wall -Wextra -pedantic ...
In findContactIndex,
value == 1;
is wrong. You were probably going for
value = 1;
but it should be
value = i;
break;
or just
return i;
since the function should return the index of the match. That means
int value = 0;
...
if (value == 1) {
return value;
}
if (value == 0) {
return -1;
}
should be
int value = -1;
...
return value;
or just
return -1;
Unrelated to your question, in findContactIndex,
if (...);{
should be
if (...) {
As you currently have it, the result of the conditional expression is disregarded, then the following block is executed unconditionally.
Unrelated to your question, in findContactIndex,
contacts[i].numbers.cell == cellNum
should be
strcmp(contacts[i].numbers.cell, cellNum) == 0
You are currently comparing the pointers instead of the strings.
Fixed:
int findContactIndex(const struct Contact contacts[], int size, const char cellNum[])
{
int i;
for (i=0; i<size; ++i) {
if (strcmp(contacts[i].numbers.cell, cellNum) == 0) {
return i;
}
}
return -1;
}
So I have been trying to make sure that I can check whether an user-inputted word is a palindrome or not by using function prototypes. However, I am getting an error in the end saying "Segment Fault: 11". I am fairly new to using function prototypes so if anyone can help me with solving anything that can be going on in the body of the function definition, then please point it out to me.
#include <stdio.h>
void palindrome_check(int ch_length, char text)
int main(void)
{
int length;
printf("Enter how many characters are in the message: ");
scanf("%d", &length);
char m;
printf("Enter the message: ");
scanf("%c", &text);
palindrome_check(l, m);
return 0;
}
void palindrome_check(int ch_length, char text)
{
char msg[ch_length];
text = msg[ch_length];
int count = 0;
while (count < ch_length)
{
count++;
scanf("%c", &msg[count]);
}
int i, j;
for (i = 0; i < ch_length; i++)
{
msg[j] = msg[ch_length - i];
}
if (text[i] == text[j])
{
printf("The message you entered is a palindrome!\n");
}
else
{
printf("It's not a palindrome.\n");
}
}
I couldn't understand some of your code it seemed you were doing some unnecessary things. What was msg for? This should work if I understood your problem correctly:
#include <stdio.h>
#include <string.h>
void palindrome_check(int ch_length, char text []);
int main(void)
{
char text [100];
/*
int length;
printf("Enter how many characters are in the message: ");
scanf("%d", &length);
Not necessary if you use strlen()*/
printf("Enter the message: ");
fgets(text,100,stdin); /*Using fgets() to allow spaces input*/
/*Strip the newline*/
text [strlen(text)-1]='\0';
palindrome_check(strlen(text),text);
return 0;
}
void palindrome_check(int ch_length, char text [])
{
int i;
for (i = 0; i < ch_length; i++)
{
if(text [i] != text [ch_length-i-1])
{
printf("It's not a palindrome.\n");
return;
}
}
printf("It is a palindrome!\n");
}
Does anyone know why my code is printing "Incorrect PIN entered"
after the if statement, instead of "Correct PIN entered"? When I change the if statement to (input_pin != current_pin) it works.
#include <stdio.h>
#define PIN_SIZE 4
main()
{
int input_pin[PIN_SIZE];
int current_pin[PIN_SIZE] = {1,2,3,4};
int i;
for(i = 0; i < PIN_SIZE; i++)
{
printf("Enter PIN %d: ", i+1);
scanf("%d", &input_pin[i]);
}
if(input_pin == current_pin)
{
printf("\nCorrect PIN entered.\n");
}
else
{
printf("\nIncorrect PIN entered!\n");
}
flushall();
getchar();
}
The if(input_pin == current_pin) is comparing two integer arrays. In C, arrays are represented internally as pointers. It's just as if you were comparing two int * variables. Because input_pin and current_pin are actually different arrays, the two pointers will never compare as equal.
To accomplish the comparison you're trying to make, you will need to compare each element of each PIN individually.
You do not have to use an array in this case
#include <stdio.h>
int main()
{
int input_pin = 0;
int current_pin = 1234;
printf("Enter PIN: ");
if ( ( scanf("%d", &input_pin)) == 1) { // successful scanf == 1. one item read
if(input_pin == current_pin)
{
printf("\nCorrect PIN entered.\n");
}
else
{
printf("\nIncorrect PIN entered!\n");
}
getchar();
}
}
EDIT:
Using a char array will be easier as strcmp will compare all the elements. If all the elements match, strcmp will return 0. the char arrays must be '\0' terminated.
#include<stdio.h>
#include<string.h>
#define PIN_SIZE 4
int main()
{
int i = 0;
char input_pin[PIN_SIZE+1] = {0}; // PINSIZE+1 to allow for terminating '\0'. set all elements five elements to 0
char current_pin[PIN_SIZE+1] = {"1234"};
for( i = 0; i < PIN_SIZE; i++)
{
printf("Enter PIN %d: ", i+1);
scanf(" %c", &input_pin[i]); // skip whitespace scan one character
}
if(strcmp( input_pin,current_pin) == 0) // if all elements match == 0
{
printf("\nCorrect PIN entered.\n");
}
else
{
printf("\nIncorrect PIN entered!\n");
}
getchar();
return 0;
}
An int array can be used but a flag will be needed allow for checking each element
#include<stdio.h>
#include<string.h>
#define PIN_SIZE 4
int main()
{
int i = 0;
int isMatch = 1; // flag to check matching elements
int input_pin[PIN_SIZE] = {0}; // set all elements to 0
int current_pin[PIN_SIZE] = {1,2,3,4};
for( i = 0; i < PIN_SIZE; i++)
{
printf("Enter PIN %d: ", i+1);
scanf("%d", &input_pin[i]);
if( input_pin[i] != current_pin[i]) // check each element
{
isMatch = 0; // if an element does not match, reset to 0
}
}
if( isMatch == 1) // isMatch did not get reset to 0
{
printf("\nCorrect PIN entered.\n");
}
else
{
printf("\nIncorrect PIN entered!\n");
}
getchar();
return 0;
}