Some logical error always executes if block? [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
#include<stdio.h>
#include<string.h>
char Sys_Pass[]="3699";
char verify_Pass(char *P,char *Q)
{
char ch;
ch=strcmp(P,Q);
printf("String Cmp %s,%s is %c %d\n",P,Q,ch,ch);
if(ch==0)
return 1;
else
return 0;
}
void main()
{
char Pass[10],New[10];
char fp=0,sp=0;
printf("Enter Password : ");
scanf("%s",Pass);
if(fp=verify_Pass(Pass,Sys_Pass))
{
Change: printf("Enter a New Password : ");
scanf("%s",Pass);
printf("Re-Type New Password : ");
scanf("%s",New);
if(sp=verify_Pass(Pass,New))
{
strcpy(Sys_Pass,New);
printf("Password Successfully changed\n");
printf("New Password : %s\n",Sys_Pass);
}
else
printf("Passwords Mismatch\n");
}
else
{
if(strcmp(Pass,"111999")==0);
goto Change;
printf("Wrong Password !!!\n");
}
printf("Fp : %c %d\nSp : %c %d\n",fp,fp,sp,sp);
}
This code is always executing the if block and provides the password change even though wrong current password is typed I want to know if there is a logical error if any ?
I am working on a 8051 project which i want to establish a secret password change i.e if i forgot a password and i type password as 111999 it should direct me to the password change menu but here it is always directing to change password menu. This was actually embedded C code but I tried to rectify that using C code but produces same output in both the cases.

You have a stray semicolon:
// here ---------------v
if(strcmp(Pass,"111999")==0);
goto Change;
As an aside, this is not a good use of goto. The better thing to do is check for either the current password or 111999 in the if condition.
printf("Enter Password : ");
scanf("%s",Pass);
if ((strcmp(Pass,"111999")==0) || (strcmp(Pass,Sys_Pass)==0))
{
printf("Enter a New Password : ");
...
}
else
{
printf("Wrong Password !!!\n");
}

There are several things in this code that have margin for improvement, but I will start by asking if you have used a debugger to debug the issue. If you haven't, you can check gdb: video here
I think also you should consider changing your main so it returns an int, except if you have a very good reason not to do it. Then you could have return codes. Same applies for the input arguments to main. If it receives none, I would strongly encourage you to specify it by typingint main(void). See here for more info
Personally I always add braces around every if/else block, even when it is one line. It helps avoid mistakes.
I dont have anything against the goto statement if it is used properly, but I believe in this case it is not. The Clean Code book by Robert Martin contains some good explanations on how to use it. I think you can try to rewrite this and avoid goto usage.

Related

i want the program to ask user which payment method they wanna use (ONLINE/CARD) . But my code will show the wrong output [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 23 days ago.
Improve this question
void Payment(){
do{
printf("\nPLEASE ENTER YOUR PREFERED PAYMENT METHOD (ONLINE/CARD):");
scanf("%s", &PaymentMethod);
if(strcmp(PaymentMethod, "CARD")){
Option = 1;
printf("\nYOU HAVE SELECTED CARD PAYMENT METHOD");
}
else if(strcmp(PaymentMethod, "ONLINE")){
Option = 1;
printf("\nYOU HAVE SELECTED ONLINE PAYMENT METHOD");
printf("\n|DRUM E-BOOK ACCOUNT DETAILS : 6734-343-8621 (GOODBANK BERHAD)");
printf("\nYOU HAVE SELECTED CARD PAYMENT METHOD");
}
else{
printf("\nYOU HAVE ENTERED WRONG PAYMENT METHOD! PLEASE TRY AGAIN");
Option=0;
}
}while(Option == 0);
printf("\nPress any number to continue:");
scanf("%d", &Option);
Receipt();
each time i choose CARD , it will show the ONLINE output and show the opposite if i choose ONLINE
if(strcmp(PaymentMethod, "CARD"))
is equivalent to:
if (strcmp(PaymentMethod, "CARD") != 0)
strcmp returns 0 on equality, but the if construct considers zero to be false, so the block is never entered.
Change the condition to:
if (strcmp(PaymentMethod, "CARD") == 0)
Re: "should i change to PaymentMethod == "CARD"?"
Answer: No, you can't compare strings with the equality == operator. That only compares the pointer values.
Also note that you do not need to use the & operator with the %s format specifier in the call to scanf.

C program compiles but console screen gives a black screen [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I'm new in C coding and I just wrote a C program, but when I tried to run the code, it gave a black screen. What do I need to change in my code to fix this problem?
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int islemler(){
int x,y,z,c,s0,s1,s2,s3;
printf("Merhaba, matematik islemlerine baslamak icinn lutfen ilk sayiyi giriniz...\n"); /*wants to first number*/
scanf("%d", &x);
printf("Simdi ise ikinci sayiyi giriniz...\n"); /*wants to second number*/
scanf("%d", &y);
printf("Son olarak 3. sayiyi giriniz...\n"); /*wants to thirth number*/
scanf("%d", &z);
printf("Yapacaginiz islemi secmek icin lutfen bir sayi seciniz...\n 1-----Toplama\n 2-----Cikarma\n 3-----Carpma\n 4-----Bolme"); /*Prompts the user to select an action. 1- addition 2- subtraction 3- multiplication 4- division*/
scanf("%d", &c);
s0= x+y+z;
s1= x-y-z;
s2= x*y*z;
s3= x/y/z;
if (c==1){
printf("Sonucunuz %d", s0); /*give answers*/
}
if (c==2){
printf("Sonucunuz %d", s1);
}
if (c==3){
printf("Sonucunuz %d", s2);
}
if (c==4){
printf("Sonucunuz %d", s3);
}
}
int main(){
int islemler();
return 0;
}
int main(){
int islemler();
return 0;
}
You basically declare islemler and then return. It does nothing. I think you wanted to call islemler and not declare it. Remove the int from that. Make it islemler():
int main() {
islemler();
return 0;
}
In your code, you're declaring it. Which is basically like letting the compiler know that the function exists somewhere and not to worry. And it also helps to catch incorrect calls to functions. They are only required in certain situations when the compiler has no way to know that a function exist. If it occurs later on or if it is in a different compilation unit, it's a good practice to declare the prototype like you have done. It does not call the function. And is also completely unnecessary here.
Also, the islemler function should return an int but doesn't return anything. You should get a warning about this. Do not ignore warnings.

How to solve "control reaches end of non-void function" warning? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
so in this function of mine, it is spitting out this warning: "carboard.c:79:1: warning: control reaches end of non-void function [-Wreturn-type]". Program runs fine, but i just want it to compile cleanly.
here is the code of the function:
int loadMainMenu()
{
char choice[LINE + EXTRA_SPACES];
Boolean menu = TRUE;
printf("\nWelcome to Car Board\n");
printf("--------------------\n");
printf("1. Play Game\n");
printf("2. Show Student's Information\n");
printf("3. Quit\n");
printf("\n");
printf("Please Enter Your Choice:\n");
do
{
int input;
fgets(choice, LINE + EXTRA_SPACES, stdin);
if (choice[strlen(choice) - 1] != '\n')
{
printf("BUFFER OVERFLOW!\n\n");
readRestOfLine();
}
choice[strlen(choice) - 1] = 0;
input = atoi(choice);
switch(input)
{
case 1: playGame();
break;
case 2: showStudentInformation();
loadMainMenu();
break;
case 3:
printf("Bye bye! \n");
return EXIT_SUCCESS;
break;
default: printf("Invalid input\n");
loadMainMenu();
break;
}
}while(menu);
}
You need to have a return statement in your code. Since your function is returning an integer you must have something likek return x; where x is an integer or you can declare function void.
The compiler is not that smart to figure out the do ... while never terminates.
To fix this, first ensure the loop cannot end by making it guaranted infinite using a constant:
do {
} while ( true );
If that doesn't work, try
while ( true ) {
...
}
The compiler might require a specific pattern ( for ( ; ; ) might also be worth a try; it is also a matter of personal preference).
If that still does not work, just return 0; after the loop above. That might be optimised away, so no extra code at best. At worst, you have to live with some dangling code.
An alternative would be to temporarily disable the warning using a pragma. That should really only be the last ressort.

I need a function that ask the user to enter a pin and after 3 wrong attempts, they program terminates

I have to write an ATM program for a class, and i cant figure out how to make a function that will ask the user for a pin and if the pin is entered incorrectly three times the program will display an exit message then terminate.... this is what i have some far. I think my issue is i don't know the correct syntax to handle my issue.
I know i will need a for loop but not sure how exactly to construct it.
void validate_acc(){
int user_acc_try;
printf("Please enter your account number: ");
scanf("%d", &user_acc_try);
if(user_acc_try != account_number){
printf("You entered the wrong account number");
}
else{
printf("");
}
}
void validate_pin(){
int user_pin_try;
printf("Please enter your pin number: ");
scanf("%d", &user_pin_try);
if(user_pin_try != pin){
printf("You entered the wrong pin number.");
}
else{
printf("");
}
}
void validate(){
validate_acc();
validate_pin();
}
Secondly, since i can only post every 90 minutes might as well ask another question, I do not know how to make a function go back to the beginning of my program like for example say after an deposit, what is the logic i would need to use to have a function go back to the beginning of my main function. I know of goto labels, that didnt seem to work when i put it in front of my main function like so...
MAIN:
int main()
i would put goto main; in another function and i would get a.... Main is not defined error. I have read a few different questions on here about labels but cant find anything that helps, if someone could guide me in the right direction, you would be giving me a great deal of relief.
thank you in advance.
It's a good idea to write out a flow chart for things like this if you can't figure out how to do it in code.
Please do not use labels/goto in C. It's a nasty habit and it's not needed.
You know how to use if statements to make a decision; think about how you would use a while loop to try to make the same decision over and over again until something changes. For instance, in pseudo-code (because I don't want to do your work for you)
user_has_not_entered_correct_pin = true
retries_left = 3
while retries_left > 0 and user_has_not_entered_correct_pin:
get pin
if pin_is_not_correct(pin) retries = retries - 1
else user_has_not_entered_correct_pin = false
end while
I am limited on time right now, so I will just post a quick help. I would suggest start researching loops in C. Since this is for a class, the book you are using should have information in it about for loops and while loops, but if not, a simple Google search can help a lot.
With a quick search on Google, this site seemed like a decent site for basic information on loops:
Loops in C
It has links and examples of using a for loop, a while loop, a do...while loop and nested loops which should help you solve your problem.
Edited to add:
In your post you mentioned that you think the problem is that you don't know the syntax that you need. It is for that reason that I pointed you to a location that can help you with the syntax that you need to solve your problem rather than show you directly how to solve the problem. I hope that this helps you not only with this question, but going forward in your class as well.
Keep a count variable like I have did below and check the number of attempts:
I don't see a need for goto here. The same logic can be used for checking pin also.
int i=0;
while(1)
{
if(i>2)
{
printf("Maximum attempts reached\n");
break;
}
printf("Enter the acc_num\n");
scanf("%d", &user_acc_try);
if(acc_num == saved_acc_num)
{
// Do your stuff
}
i++;
}
Return value from validate_pin() int validate_pin(){... return 0; .... return 1;} and test it in the main() or your validate().
int i=0;
int result=0;
while ( (result==0)&&(i<3) ){
result=validate_pin();
i++;
}
Dont use goto, learn to use loops.

I am getting runtime error (SIGSEGV) in a c program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Why I am getting runtime error (SIGSEGV) on the following code:
#include<stdio.h>
#include<string.h>
int main()
{
int t_line,count[10000],i;
scanf("%d",&t_line);
for(i=1;i<=t_line;i++)
{
fflush(stdin);
gets(t);
count[i]=(int)t[0]+(int)t[1]+(int)t[2];
}
for(i=1;i<=t_line;i++)
printf("%d\n",count[i]);
return 0;
}
I have also tried to solve this problem by initialized all the elements of array.
I am wondering how the code compiled, without declaration of the variable t. But, still the only missing elemnt was: char t[your choice of size];. Apart from that
#include<stdio.h>
//#include<string.h> No need of this header,a s you are not using any string functions
int main()
{
int t_line,count[10000],i;
char t[64];//you need to declare the variable before using it
scanf("%d",&t_line);
//Its safer if you check this
if(t_line >= 10000)//if you use 0 and < t_line in for loop below then change the condition to: if(t_line > 10000)
{
printf("ERROR: Limit exceeded. Not enough memory.\n");
return 1;//or you could use exit(1); and #include <stdlib.h>
}
for(i=1;i<=t_line;i++)//suggested: for(i=0;i<t_line;i++)
{
//fflush(stdin);
//gets(t);
char *rc = fgets(t, sizeof(t), stdin);
if(rc != NULL)
{ t[strlen(t) - 1] = '\0';\\because fgets gets the \n into the string too. This line makes fgets similar to gets, improving safety from overflow.
}
else
{
// handle fgets failed error
}
count[i]=(int)t[0]+(int)t[1]+(int)t[2];
}
for(i=1;i<=t_line;i++)//suggested: for(i=0;i<t_line;i++)
printf("%d\n",count[i]);
return 0;
}
Find the solution and suggested changes inline as code comments.
In C, its better to use indexes starting from 0, unless there is a specific requirement to use other values.

Resources