How can I resolve Code will be never executed error - c

I am making a program that reads input from a user then check the validity,
but for the while statement in the validateInput function I am getting an warning
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int ValidateUser(char *);
int ValidateInput(int);
FILE *database;
struct{
int year;
int unit;
float gpa;
char semester;
char grade;
char name[40];
}student;
int ValidateInput(int x)
{
while (x != 1 || x != 2 || x != 3) // code that causing a warning
return x;
}
int ValidateUser(char *input)
{
int result;
result = strcmp(input, student.name);
if (result == 0)
{
return 1;
}
else
{
while (result != 0)
{
printf("The Username you entered does not exit. Please enter correct name.");
}
}
return 1;
}
int main()
{
printf("\t----------------------------------------------------------\n");
printf("\t|\t\t\t\t Santa Monica College\t\t\t\t\t |\n");
printf("\t----------------------------------------------------------\n\n");
printf("\t\tWelcome to Santa Monica Student Record System.\n\n");
printf("Please Enter Your Option\n");
printf("\t1.View GPA/GRADE\n");
printf("\t2.Add New GPA\n");
printf("\t3.Modify Information\n");
int choice;
scanf("%d", &choice);
char UserName[40];
if(choice == 1)
{
printf("Please enter your name\n");
scanf("%s", UserName);
ValidateUser(UserName);
printf("The GPA of %s is %f , %c ", student.name, student.gpa, student.grade);
}
else if (choice == 2)
{
printf("Please enter your name\n");
scanf("%s", UserName);
ValidateUser(UserName);
}
else if (choice == 3)
{
printf("Please enter your name\n");
scanf("%s", UserName);
ValidateUser(UserName);
}
else
{
ValidateInput(choice);
}
return 0;
}
The ide was suggesting to add parentheses around x-values in the argument of while statement in the ValidateUser to make it silence
I've done some research on this warning and I found that the condition I made is not true so that's why I am getting it, but I am not quite sure what the problem is.
Can someone help me out with this???

In validateUser(), your program will reach the
while (result != 0)
only in the event that the while condition is initially true, so if it reaches the loop, it will enter it. The body of the loop does not modify result, so if it enters the loop, it will loop indefinitely.
Ultimately, if the first branch of the if / else is taken, then the function returns from within that branch, and if the second branch is taken then control never exits that branch. Either way, the
return 1;
at the end of that function cannot be reached. Of course, that's just a symptom. The infinite loop is the main problem.
It's unclear what behavior you actually want here, but what would be most in keeping with the name of the function would be for it to only evaluate whether the specified user name is valid, returning a result that conveys either "yes" or "no". There is no particular reason why such a function would need to loop at all.

You put while (result != 0) inside function ValidateUser(char *input) and never put a way to get out of the loop, resulting in the return value below it never running.
To fix this, you would need to add a break; somewhere in the loop to indicate that you are ready to leave the current loop, or make result = 0;
The difference between the two is that break; will indicate that the rest of the loop doesn't need to run and will jump out of the loop, or use result=0; to run the rest of the code in the loop and then jump out of it

Related

Can't get while loop to work 2 times? (C)

So I'm trying to loop the name asking section as well as the age one, the age one worked fine but when I tried to do it with name one it doesn't work. What I'm just trying to achieve is that when you put a number in the name section or vice versa, you get an error message and it loops you back to the same question
#include <stdio.h>
int vek;
char name[20];
int result1;
int result2;
int main()
{
FindName();
void FindName() { // it wants me to put a ";" which doesn't make sense to me and doesn't work
printf("Napis svoje meno \n");
result2 = scanf("%s",&name);
while (gethar() != '\n');
if(result2 == 1){
printf("Ahoj %s \n",name);
break;
system("pause");
}
else {
printf("nepis sem cisla ty kokot \n");
}
findAge();
}
void findAge() {
printf("Napis svoj vek \n");
result1 = scanf("%d",&vek);
while (getchar() != '\n');
if(result1 == 1){
printf("%s si krasny %d rocny priklad downoveho syndromu \n ",&name,vek);
}
else {
printf("co si jebnuty \n");
findAge();
}
}
I've tried to just break the loop if it's the right answer but that wouldn't work either, I'm just a beginner
The while loop will run everything inside the body as long as the condition is true. You need to put the code that needs to be repeated in a block, between { and }. You've put a semicolon behind it. That means a null statement, or do nothing. That way the condition is checked until it is no longer true, but nothing else is done. For example:
int i=0;
while(i < 3) {
printf("%d\n", i);
i++;
}
That will print the numbers 0,1 and 2. And then it stops because the condition is no longer true.
You want the program to look like this. In pseudocode:
main:
call findName
call findAge
findName:
print "Something Eastern European asking for a name"
result = 0;
while result != 1:
result = read input
if result == 0
print "Try again"
And the same for findAge
Notice the functions never call themselves. They just run the loop until the input is valid.

While loop misbehaving,

i am pretty new to c, i m trying to make the user input a number, but if they input a letter or word it shows a warning and asks for input again, my code works fine if the user puts in a number but it goes into an infinite loop if the user inputs something invalid, here is my code
#include <stdio.h>
int main(void) {
float salary;
int status = 0;
while (status == 0)
{
printf(" Please input your yearly salary to calculate taxes: \n");
status = scanf(" %f", &salary);
if (status == 0)
printf("invalid input!\n");
}
printf("%.2f\n", salary);
return 0;
}
i thought that i was something to do with the buffer left over from the first scanf , but adding a space " %f" didnt work, i tried using fflush(stdin) after then scanf also didnt work. i m not sure what else i can try.
thanks in advance for any help.
You need to clear the buffer or it will keep evaluating it and cause the endless loop. Add one line after your invalid input: scanf("%*[^\n]")
#include <stdio.h>
int main(void) {
float salary;
int status = 0;
while (status == 0)
{
printf(" Please input your yearly salary to calculate taxes: \n");
status = scanf(" %f", &salary);
if (status == 0)
printf("invalid input!\n");
scanf("%*[^\n]");
}
printf("%.2f\n", salary);
return 0;
}
This will work. You can see a better explanation here: Scanf and loops
The problem is that scanf won't advance the file stream. You ask it to read a floating point value and it isn't able to, so it doesn't consume the input.
For example, let's say your input is "foo", which isn't a number. Your scanf call isn't able to successfully read anything and returns 0. Then, in the next iteration, "foo" is still waiting to be read from stdin.
Try changing your if condition to something like
if (status == 0) {
char foo[256];
fgets(foo, sizeof(foo), stdin);
printf("Invalid input! Expected a nmuber, got: %s", foo);
}
Notice how the entire input is read from stdin by the gets call.

While Loop is running twice in C

I Have written a simple while program in C
// Online C compiler to run C online.
// Write C code in this online editor and run it.
#include <stdio.h>
typedef enum
{
false = 0,
true = 1
} bool;
int main() {
bool res = true;
while (res)
{
char choice;
printf("Success! \n");
printf("Do you want to continue(y/n): ");
scanf("%c", &choice);
if (choice == 'N' || choice == 'n')
{
res = false;
}
}
printf("Good Bye");
}
The Program run successfully but when I type Y in Do you want to continue the loop is executed twice. How Can I Solve this?
Add a space before %c in scanf it skip all whitspaces(newline) like
scanf(" %c", &choice);
^
when I type Y in Do you want to continue the loop is executed twice ?
When you type Y+enter this will go like "Y\n" and this new line will taked by next iteration, so use above meathod to discard it.
Similiar Questions :
1)scanf() leaves the new line char in the buffer
Thanks.

check input program gets stuck in an infinte loop

I'm trying to create a program that asks to type something and check if it is an integer. If it is an integer, then print "the integer is ...". Else, print "try again" and waits for another input. However, the program prints an infinite number of "try again" if you type in a character. Here's the source code:
#include <stdio.h>
#include <stdbool.h>
int main()
{
int inp;
bool t = 1;
printf("type an integer\n");
while (t) {
if (scanf("%i", &inp) == 1) {
printf("The integer is %i", inp);
t = 0;
} else {
printf("try again");
scanf("%i", &inp);
}
}
}
OP's code fail to consume the offending non-numeric input. It remains in stdin, for the next input function. As it is unfortunately just another scanf("%i", &inp) which fails the same way - infinite loop.
After attempting to read an int, read the rest of the line.
#include <stdio.h>
#include <stdbool.h>
int main() {
int inp;
int scan_count;
printf("Type an integer\n");
do {
scan_count = scanf("%i", &inp); // 1, 0, or EOF
// consume rest of line
int ch;
while ((ch == fgetchar()) != '\n' && ch != EOF) {
;
}
} while (scan_count == 0);
if (scan_count == 1) {
printf("The integer is %i\n", inp);
} else {
puts("End of file or error");
}
}
An even better approach would read the line of user input with fgets(). Example
When you entered a char, the variable inp in scanf("%d", &inp) would get null, since the input that doesn't match the format string. And the character you input would remain in the buffer, so that's the reason both your scanf would not stop.
A simplest way to fix this is modify your second scanf("%i", &inp); to scanf("%c", &c); (don't forget to declare a char c in your main function).
check here while(t) its in an infinite loop because you have to set a condition for t something like while(t==1) or while(t>1) or (t<1) something like that. saying while(t) means that t can be anything and it will continue to run.
There is nothing in to break the while loop.
consider getting rid of the boolean, and simply using a while (1) loop with a break. Also you should be using "%d" to indicate an integer in scanf/printf. And there is no need for the scanf call in the else, since your program would loop back and call scanf again anyway.
#include <stdio.h>
int main() {
int inp = 0;
printf("type an integer\n");
while (1) {
if (scanf("%d", &inp) == 1) {
printf("The integer is %d", inp);
break;
}
else {
printf("try again");
}
}
return 0;
}
I hope this helped.

Repeating an Input till it is answered Correct

The concept if very simple. The computer must repeat the question till it recieves a valid response. Here is my current code:
#include <stdio.h>
int main(int argc, const char * argv[]) {
int age;
do{
printf("How old are you?\n");
scanf("%d", &age);
if (age == 32767)
{
printf("Error, retry: \n");
}
else
{
printf("Cool.");
break;
}
}
while(age!=3267);
return (0);
}
The if else statement is to catch the exception incase the user types something that is not an integer.
I tried using a do-while loop but it ended up as an infinite loop
I used the do-while loop because I needed to go through that procedure until I get a valid age value.
My output with the current code is:
How old are you?
g
Error, retry:
How old are you?
Error, retry:
How old are you?
Error, retry:
How old are you?
Error, retry:
It goes like this indefinitely.
It would be great if you could help me out.
The computer must repeat the question till it recieves a valid response.
It (output) goes like this indefinitely.
Reason :
The problem is that you are receiving input only once in your code and then entering into loop to check for the age.
since age value is not re-assigned after every iteration, if the first intput is !=32767 it's always wrong and enters into an infinite loop or also known as the odd loop.
scanf("%d", &age); //scans only once
do //enters loop
{
if (age == 32767)
{
printf("Error, retry: \n");
}
else
{
printf("Cool.");
}
} while(age!=32767);
The if else statement is to catch the exception incase the user types something that is not an integer.
No, if (age == 32767) would only check if the entered response was equal to 32767 or not.
From #davmac 's comment , you can never check for an input value greater than the maximum value of the int variable.
Instead it'd be better if you would assign a range this way
`if (age > 100 || age <0 )`
Solution :
to avoid this scan age for every iteration and also see the changes I've done :
do{
printf("How old are you?\n");
if(scanf("%d", &age)==1) //checking if scanf is successful or not
{
if (age > 100 || age <0 )
{
printf("Error, retry: \n");
}
else
{
printf("Cool.");
break; //break loop when correct value is entered
}
}
else //if scanf is unsuccessful
{
char c;
printf("enter only integers\n");
do
{
scanf("%c",&c);
}while( c !='\n' && c!= EOF ); //consuming characters
}
}while(1); //always true
Some important points:
First, Using scanf to read an int from user input usually allows for whitespace to be entered first:
scanf(" %d", &age);
In particular this skips over previous new line characters that were input previously and are still buffered.
Second, scanf returns a value indicating whether it succeeded or failed, and how many items it matched. You need to check this return value:
int r = scanf(" %d", &age);
if (r == EOF) {
break;
}
if (r == 0) {
printf("Error, retry: \n");
}
Third, if scanf can't match input it is left in the input buffer. If you don't retrieve it from the buffer, it will simply fail to match again the next time you call scanf, ad infinitum. For this reason, scanf is not great for handling user input at all. It is better, if possible, to read a single line of input into a buffer (you can use fgets for this, if you are careful), and then process the buffer. As a weak alternative, you can force some of the input buffer to be consumed by scanning for a string before you try to read the input value again:
int r = scanf(" %d", &age);
if (r == EOF) {
break;
}
if (r == 0) {
printf("Error, retry: \n");
scanf("%*s"); // match string but suppress assignment
}
else {
printf("Cool.\n");
break;
}
This modification gets your code to at least halfway-working state.
Use do while Loop. Like:
Do{
// your code
Age = // asign value
}while(age>100 && age < 1);
So it will repeat until age is entered between 100 and 1. It will stop if it will get age b/w 1 - 100.
Thanks. Hope it will help.

Resources