Can't get while loop to work 2 times? (C) - 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.

Related

How can I resolve Code will be never executed error

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

Validating integer values; c program

I need to program a code that asks the user to input valid positive integer values and then display error messages when it is not an integer for ex. if it is either a 0 , -1, or character/string. I tried making a do while loop so that it continues to scan again if the input is wrong, but it keeps an infinite loop. And this after this I need to take this value and plug it into a conversion function that I already have. How do I do that? Here is my code so far:
#include <stdio.h>
int scanf(const char *format, ...);
int user_interface();
double convert(double);
void print_table(int);
int user_interface()
{
int Kelvin;
char term;
int status;
int wrong = 0;
printf("\t\n");
printf("Hello, and welcome to homework1a program where\n");
printf("this program will request input from the user to\n");
printf("enter a value for Kelvin and then it will return\n");
printf("the acquired integer\n");
printf("\t\n");
do
{
printf("Enter a maximum value to show: ");
fflush(stdin);
status = scanf("%d%c", &Kelvin, &term);
if(status < 0)
{
printf("WRONG This is not correct %d\n", Kelvin);
wrong = 1;
}
else if((status) != 2 || term != '\n')
{
printf("Error: %d\n", Kelvin);
wrong = 1;
}
} while (wrong);
return 0;
}
int main(int argc, char *argv[])
{
void print_table(int num);
double convert(double Kelvin);
user_interface();
return 0;
}
1. Program getting stuck in a loop after wrong input.
So pretty much right now in your do-while loop you are using the "wrong" variable to determine if it should loop over again.
You have only been setting it to 1 when it is incorrect. It is getting stuck in a loop as the "wrong" variable is never being set back to 0.
In the do-while loop you need somewhere to include "wrong = 0;"
It is up to you where you choose to do this, you can either put it at the beginning of the do-while loop OR after the else if statement you can add an else statement.
else
{
wrong = 0;
}
Up to you how you want to implement it :) but just make sure the "wrong" variable gets reset or else once the user puts in the incorrect input 1 time the program will keep looping since the variable has not reset.
2. How to get the value into your conversion function.
So right now your "conversion" function can take in a double and the "user_interface" function returns an int so you can probably have the return statement plug in the value into the "conversion" function, but in saying that if you were expecting to receive a double in the "conversion" function I would recommend re-evaluating if the "user_interface" should be returning an int or a double.
Hoped 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.

Issue with a nested for loop

I'm currently working on a program that asks a user to enter a secret word. The user's input is then compared with a list of words which are on a text file. The user has 3 chances to enter the word. If correct, the program restarts the loop. This continues until all the words have been guessed correctly. If a word is incorrectly guessed 3 times, the program should terminate. My problem is with the 3 guesses loop. I can get it to work if it is not nested in the while loop however with the while loop it's continues to ask for the incorrect word. What am I missing? Here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
//Step 1: open file and declare variables//
FILE *fp;
fp = fopen("secretwords.txt","r");
char guess[20];
char secret[20];
int i;
//Step 2: Check that file opened correctly, terminate if not//
if (fp == NULL)
{
printf("Error reading file\n");
exit (0);
fclose(fp);
}
//Step 3: Create loop to run for each word to run to end of file//
while(fscanf(fp,"%s", secret)!=EOF)
{
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct\n");
break;
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
}
return 0;
}
When you do break, you break from the for loop, but not from the while loop.
To solve it, you can either change the design to have one loop only, or you should have the break instruction in the outer loop too.
You did not do break in the following part:
else
{
if(i == 2)
break;
printf("Your guess was incorrect. Please try again\n");
}
Hint: if the user has had 3 misses, the value of i after the for loop will equal to 3. This is your chance to do something (terminate the program).

Compare user input with text file in C

I need to have a user input a word then compare the word with a text file to see if it is correct. The user has 3 attempts to enter the word before the program terminates. My issue is reading the word from the file I know it's something simple that I have wrong. I should also clarify that the error I'm getting is in the compiler I haven't gotten to the point of being able to compare the strings yet!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
fp = fopen("secret.txt","r");
char guess[10];
const char secret[10];
int i, c;
c = getc(fp);
fgets(secret, sizeof(secret), fp);
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
while (c !=EOF)
{
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct");
return 0;
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
fclose (fp);
}
return 0;
}
Here are some pointers:
c = getc(fp) consumes the first character of the file, so it never becomes part of the secret variable.
If secret.txt contains a newline, the newline is read into the secret variable.
The while (c != EOF) loop seems pointless, since c isn't modified inside the loop. Furthermore, the infinite nature of the loop prevents the outer for loop from functioning correctly.
If I were you, I'd fix the while loop and would make sure that secret is read correctly, for example by printing it out or examining it in a debugger.
What is
c = getc(fp);
needed for? My "guess" would be that you read the first character of the word into c and then secret misses the first character.
EDIT: Instead of using getc for EOF checking, which as said corrupts the read word (and this while loop is rubbish anyway), just check the return value of fgets:
if(fgets(secret, sizeof(secret), fp) == NULL)
//file is empty or other error occurred
and remove this infinite while(c != EOF) loop.
So it should rather look something like:
FILE *fp = fopen("secret.txt","r");
char guess[10];
const char secret[10];
int i;
if(fgets(secret, sizeof(secret), fp) == NULL)
{
printf("Error while reading file\n");
return -1;
}
fclose(fp);
for (i=0; i < 3; i++)
{
printf("Please guess the word: \n");
scanf("%s", guess);
if (strcmp(secret,guess) == 0)
{
printf("Your guess was correct");
return 0;
}
else
printf("Your guess was incorrect. Please try again\n");
}
return 0;
Your code is grossly off: you do not alter 'c' inside a loop, making it spin indefinitely. It's a good idea to sketch your algorithm on a piece of paper before you start coding. In your case, pseudocode should look like this:
Open file
Read the secret
Close file
Repeat three times:
--- Display the prompt
--- Read user input
--- If user input matches the secret, congratulate the user and exit.
Tell the user his guess was incorrect.
At this point, converting it to C should be more or less mechanical. Good luck!
while (c !=EOF)
{
if (strcmp(secret,guess)==0)
{
printf("Your guess was correct");
return 0;
}
else
{
printf("Your guess was incorrect. Please try again\n");
}
}
looks like an infinite loop to me

Resources