My C code aint stop and i can't end the loop - c

What am I doing wrong? My code keeps in loop and n goes minus. It was supposed to return 0; at 0.Also whatever I do it starts with 3-2-1-0 even I type "2" it still keeps doing it 3-2-1-0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
static const char PSWRD[]="1234";
char p[6];
int n=3, y;
printf("Hos geldiniz");
do{
printf("\n\nOgrenci_ID:Elif");
fflush(stdout);
printf("\nSifre:");
scanf("%s", &p);
fflush(stdout);
y=strcmp(p, PSWRD);
if(y==0){
printf("\nGiris Basarili"); `//succesfull login`
return 0;
}else {
printf("Yanlis Sifre, tekrar deneyiniz", 3-n); //wrong password try again
printf("\nKalan hakkiniz ");
printf("%d\n", n);
getchar();
n--;}
if(n<1){
printf("\nHesabiniz bloke oldu");
return 0;
// that means you use all your chance and now you're blocked but my code aint stop here and n goes minus
}
// I am not exactly sure about "3"
//Also what ever i do it starts with 3-2-1-0 even i type "2" it's still keep doing it 3-2-1-0
}while (n<=3);
return 0;
}

while (n<=3);
doesn't agree with
n--;
You seem to want
while (n>0);

Its working for me!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
static const char PSWRD[]="1234";
char p[6];
int n=3, y;
printf("Welcome");
do{
printf("\n\nStudent_ID:Elif");
fflush(stdout);
printf("\nPassword:");
scanf("%s", p);
fflush(stdout);
y=strcmp(p, PSWRD);
if(y==0){
printf("\nSucessfull Login\n"); //succesfull login
return 0;
}else{
n--;
printf("\nWrong password, try again: "); //wrong password try again
printf("\nRemaining attempts ");
printf("%d\n", n);
getchar();
}
if(n<1){
printf("\nYour account has been blocked\n");
return 0;
}
}while (n>0);
}
When user introduces wrong password, you have more 2 tries and if you enter the password wrong on thats 2 tries program ends! But if you insert it right program makes login, so works fine

In your code, there is no increment of 'n', so the loop keeps going (because n is always smaller than 3). I'm not too sure of what you're trying to do, but you need to change your 'while' condition or statements of 'n' inside the loop.
Currently the loop keeps running forever:
When n=3 - > 3<=3 is true.
When n=2 - > 2<=3 is true.
Etc.
The only way it's going to end is when n decrements until it is equal to the absolute minimum value of an integer which is -2,147,483,648, then it will decrement one more time and change to 2,147,483,647 and the loop will end.

Use printf to watch the value of n, and you will quickly observe that your condition for the do...while loop is incorrect.
However, note the conditional, if(n<=0) with return.
Provide a minimal reproducible example, such as below...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int login(char* PSWRD)
{
int n=3, y;
char p[100+20];
printf("Hos geldiniz");
do{
printf("\nSifre:");
scanf("%100s", p); // limit input size, use p, not &p
if( 0 == strcmp(p, PSWRD) ) {
printf("\nsuccess!");
return 0;
}
printf("Yanlis Sifre, tekrar deneyiniz"); //wrong password try again
n--;
if(n<=0)
{
printf("\nHesabiniz bloke oldu");
return -1;
}
printf("n=%d\n",n); // print current n
} while (n<=3); // this should be (n>0)
return -1;
}
int main()
{
char* PASSWD = "password";
int result;
if( 0 > login(PASSWD) ) {
printf("\nfailed!\n");
exit(1);
}
printf("\nsuccess!\n");
// continue processing here
}
Caveat: Make sure you limit input size to avoid buffer overflow
Read no more than size of string with scanf()

Related

C: Function not behaving as intended when called by "if" statement

I'm a C beginner and am working on a program that registers flights using structs. Each flight has a code that must follow a certain structure: FLI-XXXX, X being integers. I'd like to use the integers part of the code later on, so I thought the best way to scan for it was using both fgets and scanf. After validating the code using auxiliary variables, I would later write it to the flights struct. However, I'm stuck at the validating part.
The problem is, whenever I call the function that validates a code (opt1) inside an if statement, it runs twice and only works as intended the second time around. Here's my code:
#include <stdio.h>
#include <string.h>
typedef struct
{
int num;
char code[5];
}fl;
fl flight[9999];
int Valid(char a[], int b)
{
if((strlen(a) != 4) || (b<0 || b>9999)){
return 0;
}
else if(a[0] !='F' || a[1] !='L' || a[2] !='I' || a[3] != '-'){
return 0;
}
return 1;
}
void opt1(fl a[]){
char tempCode[5];
int tempNum;
do
{
puts("Insert code:");
fgets(tempCode, 5, stdin);
scanf("%d", &tempNum);
puts("");
if (Valid(tempCode, tempNum))
{
printf("Flight %s%d registered. \n", tempCode, tempNum);
}
else
{
puts("Flight # invalid.");
}
} while (Valid(tempCode, tempNum)==0);
}
int main() {
int opt;
//calling opt1 works as intended
opt1(flight);
//calling inside if statement runs opt1() twice, only the second time as intended
scanf("%d", &opt);
if(opt==1){
opt1(flight);
}
return 0;
}
And here's an input:
FLI-1234
1
FLI-1234
That returns:
Flight FLI-1234 registered.
Insert code:
Flight # invalid.
Insert code:
Flight FLI-1234 registered.
I'm not sure why this is happening. Can anyone guide me in the right direction, please? Thank you.

Vigener cipher, looping the key

I would like to ask your help about my program. It will be a vigenere-cipher solution, but I have to encrypt it from a file.
My problem is that I can't loop my keyword for the message length.
There are the tasks
Ask the message you want to translate,maximum 255 character
I have to transform the message to unaccented,upper case and without spaces
Than print it to the screen.
Ask the key, maximum five character and the same transformation.
I have to loop the key for the lenght of the message. than print it to the screen. Now that's what I can't do.
Can somebody please help me in it?
#include <stdio.h>
#include <ctype.h>
#define MAX 256
#define KMAX 6
void mess(void){
char message[MAX];
int j,i,k=0;
char big[]={"ÁÉÍÓÖŐÚÜŰ"}, small[]={"áéíóöőúüű"}, english[]={"aeiooouuu"};
printf("Please give the message you want to enrypt! Maximum %d character: ",MAX-1); // 1.
fgets(message,MAX,stdin); // 2.
for(i=0;message[i];i++){
j=0;
while(small[j] && (message[i]!=small[j] && message[i]!=big[j])){
j++;
}
if(small[j]){
message[i]=english[j];
}
if(isalpha(message[i])){
message[k]=toupper(message[i]); k++;
}
}
message[k]='\0';
printf("\nThe clean message is: %s\n\n",message);
}
void keyword(void){ // 3.
char key[KMAX];
int j,i,k=0;
char big[]={"ÁÉÍÓÖŐÚÜŰ"}, small[]={"áéíóöőúüű"}, english[]={"aeiooouuu"};
printf("Please give the key!Maximum %d character\n",KMAX-1);
fgets(key,KMAX,stdin);
for(i=0;key[i];i++){
j=0;
while(small[j] && (key[i]!=small[j] && key[i]!=big[j])){
j++;
}
if(small[j]){
key[i]=english[j];
}
if(isalpha(key[i])){
key[k]=toupper(key[i]); k++;
}
}
key[k]='\0';
printf("\nThe clean key is: %s\n\n",key);
}
void loop() //4.
{
}
int main(void){ // main
system("CHCP 1250");
system("CLS");
mess();
keyword();
loop();
return 0;
}

error C2447: '{' : missing function header -- Can't resolve this error, what's wrong?

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include "bcio2.h"
int error, x;
char totalimpulse[80], averageimpulse[80];
void validate_number();
int main(void)
{
clrscr();
do{
printf("\nTotal Impulse delivered: ");
gets(totalimpulse);
validate_number();
} while (error != 0);
printf("You entry %d was valid\n", x);
getch();
return 0;
}
{ //error C2447
clrscr();
do{
printf("\nAverage Impulse delivered: ");
gets(averageimpulse);
validate_number();
} while (error != 0);
printf("You entry %d was valid\n", x);
getch();
return 0;
}
The brackets seen to match and there doesn't seem to be any unnecessary semicolons. I'm assuming this is the correct way to display input/validation. It works fine when run with just the do…while(); loop for totalimpulse but when I copy/paste the exact same between another pair of { } I get just that C2447 error.
The code that starts where the error is is not inside main, or any other function for that matter. If you remove the braces on the error line and the one preceding it, then your second loop will also beside of main. If you want that section to be a different function, you have to include the header for that function. What you put at the top for validate_number is just a promise that you will define that function somewhere (although if you mean for that section at the bottom to be validate_number, I'm pretty sure you don't want it to be recursive).
Right now you just have a block of code, outside any function.
I'm assuming from the rest of your code, that this block of code is supposed to be the definition of void validate_number();, like this:
void validate_number()
{
clrscr();
do{
// ...
return 0;
}
Do note that a void function cannot return a value, so your return 0 should be removed.

Getting the error "undefined reference to". Can you explain what it means and where I have made the mistake?

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <stdio_ext.h>
#include <string.h>
#include <signal.h>
#include <pwd.h>
#include <sys/types.h>
#include <crypt.h>
#include "pwent.h"
#define TRUE 1
#define FALSE 0
#define LENGTH 16
void sighandler() {
signal(SIGINT,SIG_IGN);
}
int main(int argc, char *argv[]) {
mypwent *passwddata;
/* see pwent.h */
char important[LENGTH] = "***IMPORTANT***";
char user[LENGTH];
char prompt[] = "password: ";
char swap_prompt[]="New password: ";
char again_prompt[]="Again: ";
char *user_pass;
char *new_pass;
char *again_pass;
int f_login;
char *en_pass;
char *envp[] = { NULL };
char *argvv[] = { "/bin/sh",NULL};
sighandler();
while (TRUE) {
/* check what important variable contains - do not remove, part of buffer overflow test */
printf("Value of variable 'important' before input of login name: %s\n",
important);
printf("login: ");
fflush(NULL); /* Flush all output buffers */
__fpurge(stdin); /* Purge any data in stdin buffer */
if (fgets(user,16,stdin) == NULL) /* gets() is vulnerable to buffer */
{
exit(0); /* overflow attacks. */
}
*/* check to see if important variable is intact after input of login name - do not remove */*
printf("Value of variable 'important' after input of login name: %*.*s\n",
LENGTH - 1, LENGTH - 1, important);
user_pass = getpass(prompt);
passwddata = mygetpwnam(user);
if (passwddata != NULL) {
en_pass=crypt(user_pass,passwddata->passwd_salt);
if (!strcmp(en_pass, passwddata->passwd)) {
if(passwddata->pwage==10){
printf("You need to swap your password!!! \n");
do{
new_pass=getpass(swap_prompt);
again_pass=getpass(again_prompt);
}while(strcmp(new_pass,again_pass));
printf("Password changed!!! \n");
passwddata->passwd=new_pass;
passwddata->pwage=0;
}else{
printf(" You're in !\n");
printf("Number of failed login is %d\n", passwddata->pwfailed);
passwddata->pwfailed=0;
passwddata->pwage++;
}
mysetpwent(user,passwddata);
setuid(passwddata->uid);
execve("/bin/sh",argvv,envp);
}else{
if(passwddata->pwfailed==3){
printf("You attempted too many times \n");
passwddata->pwfailed=0;
mysetpwent(user,passwddata);
return 0;
}
printf("Wrong password, please try again!!! \n");
f_login++;
passwddata->pwfailed=f_login;
mysetpwent(user,passwddata);
}
}else{
printf("Login Incorrect \n");
}
}
return 0;
}
So I get the error "undefined reference to mygetpwnam" and "undefined reference to mysetpwent". I am not sure what this exactly means and how to go about correcting it. This is a part of an assignment I am working on with regards to unix and their password systems.
You attempt to call the function mygetpwnam once in your code, and mysetpwent three times, yet those functions are not defined anywhere. Hence, you reference something undefined, an error.
"mygetpwnam" and "mysetpwent" are defined in pwd.h. Open and check if pwd.h has definition for "mygetpwnam" and "mysetpwent".
Check pwent.h to see if your functions are declared there (definition should be in pwent.c). Also make sure you haven't misspelled the function names. You should show us how you compile the program.

Exit a loop at anytime

I'm trying to exit a loop at anytime I want by pressing any key. I've tried the code below but it can't be done. Gotta need your help. Thank you in advance. I'm using a C-Free 5.0.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int b=0, i;
int seconds;
printf("\nEnter number of seconds : ");
scanf("%d", &seconds);
while (b==0)
{
for(i=1;i<=seconds;i++)
{
time_t end = time(0) + 1;
while(time(0) < end)
;
seconds -= 1;
printf("Number of seconds left : %d\n", seconds);
b=kbhit();
}
if(seconds == 0)
{
exit(0);
}
}
printf("Number of remaining seconds left : %d\n", seconds);
}
You are "busy-waiting" in the innermost while loop. That might not be the best solution, but if that is what you want to do, you need to add a test in that loop to check if a key has been hit.
To exit a loop use a function in c++ called khbit. It becomes 1 when any key is pressed and to empty it again assign the key pressed to clear the buffer using getch()
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
while(1)
{
if(kbhit()) // khbit will become 1 on key entry.
{
break; // will break the loop
}
// Try to use some delay like sleep(100); // sleeps for 10th of second to avoid stress on CPU
}
// If you want to use khbit again then you must clear it by char dump = getch();
// This way you can also take a decision that which key was pressed like
// if(dump == 'A')
//{ cout<<"A was pressed e.t.c";}
}

Resources