how to check if user input is a certain character - c

I am trying to check if the user inputs y or something else.
I have tried creating a string and looping through what the user inputs, but that doesn't work.
char answer[] = "n";
for(int i = 0; i < sizeof(answer)/4; i++) {
if(answer[i] == "y") {
calculatorPrompt();
} else if(answer[i] === "n") {
printf("Okay, bye!");
System(100);
}
}
This is my code (I'm sure it crashes on the if statement):
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf("%s", answer);
if(answer == 'y') {
calculatorPrompt();
} else if(answer == 'n') {
printf("Okay bye!");
Sleep(100); //wait for 100 milliseconds
}
calculatorPrompt() function:
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
if(scanf("%d\n", a) != 1) {
checkNumber();
} else {
printf("Enter your second number: ");
if(scanf("%d\n", b) != 1) {
checkNumber();
} else {
sum = calculate(a, b);
printf("Your answer is: %d", sum);
}
}
}
calculate() function:
int calculate(int a, int b) {
return a + b;
}
checkNumber() function:
void checkNumber() {
printf("Really? You didn't enter a number... Now exiting..");
return;
}
I have included <windows.h> <stdio.h> and <stdbool.h>
I'm also confused as to why it crashes.
The return value of the program is -1,073,741,819.

You have multiple issues with scanf() statements in the code :
in calculatorPrompt() funtion of your code, you use :
if(scanf("%d\n", a) != 1) //wrong : sending variable as argument
This is wrong because you need to send address of the variable as the argument not the variable itself as argument.
if(scanf("%d", &a) != 1) //correct : sending address as argument
similarly change while scanning other integers in the code.
here,
char answer = 'n';
scanf("%s", answer);
As you are using the wrong format specifier, this invokes Undefined behavior.
here since answer is a char so, instead use :
scanf(" %c", &answer); //space to avoid white spaces
and as I've already suggested in the comments :
You use i < sizeof(answer)/4 in the for loop
No! it must be i < sizeof(answer), as in a string every element occupies only 1 byte not 4 (you are mistaking it for an int array)
by the way you don't have any strings in your code

I don't recommend the code you have written for calculator, yet wanted to help you find the working code. Try following code that is based on your own code. Hope you'll see the differences and understand the reasons why the program was crashing in your case.
#include <Windows.h>
#include <stdio.h>
#include <stdbool.h>
bool checkNumber(int num)
{
return true;
}
int calculate(int a, int b) {
return a + b;
}
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
scanf_s("%d", &a);
if (checkNumber(a)) {
}
printf("Enter your second number: ");
scanf_s("%d", &b);
if (checkNumber(b)) {
}
sum = calculate(a, b);
printf("Your answer is: %d", sum);
}
int main()
{
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf_s("%c", &answer);
if (answer == 'y') {
calculatorPrompt();
}
else if (answer == 'n') {
printf("Okay bye!");
Sleep(100); //wait for 100 milliseconds
}
}

#include <windows.h>
#include <stdio.h>
#include <stdbool.h>
void calculatorPrompt(void);
int main(void){
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf("%c", &answer);//scanf need address of store place
if(answer == 'y') {
calculatorPrompt();
} else if(answer == 'n') {
printf("Okay bye!\n");
Sleep(100); //wait for 100 milliseconds
}
return 0;
}
void checkNumber(void);
int calculate(int a, int b);
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
if(scanf("%d", &a) != 1) {//\n : skip white spaces and wait input not spaces
checkNumber();//call when invalid input
} else {
printf("Enter your second number: ");
if(scanf("%d", &b) != 1) {
checkNumber();
} else {
sum = calculate(a, b);
printf("Your answer is: %d\n", sum);
}
}
}
void checkNumber(void){//output message and clear input.
fprintf(stderr, "invalid input!\n");
scanf("%*[^\n]%*c");//clear upto end of line.
}
int calculate(int a, int b) {
return a + b;
}

When you scan a character , you just need to use %c. If you are planning to continue with string you must use strcmp() for comparison not ==.

Related

Is my do while loop not working due to this function?

Im making a program where it asks the user to guess a number 1-100 that the computer is thinking about.
In the end of the program, when the user has guessed the correct number, im trying to get the program to ask if user wants to play again (restart the program).
To solve this, i tried using a do while loop & char repeat;. The loop is stretching from almost the beginning of the program, until the end, althought without success. Does anyone know what im doing wrong? Is it because of the function talfunktion, that the loop won't pass?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int talfunktion (int tal, int guess, int tries, char repeat);
int main () {
do {
srand(time(NULL));
int tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char repeat;
printf("Psst, the right number is: %d \n", tal); // remove later, not relevant to uppg.
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
guess = talfunktion(tal, guess, tries, repeat);
getchar();
getchar();
return 0;
}
int talfunktion(int tal, int guess, int tries, char repeat) {
do {
if (guess < tal) {
tries++;
printf("\nYour guess is too low, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
else if (guess > tal) {
tries++;
printf("\nYour guess is too high, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
} while (guess > tal || guess < tal);
if (guess == tal) {
printf("\nCongratulations, that is correct!");
tries++;
printf("\nYou made %d attempt(s)", tries);
printf("\nPlay Again? (y/n)");
scanf("%c", &repeat);
}
} while (repeat == 'y' || repeat == 'Y');
}
This is one possible solution
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void talfunktion(int tal, int guess, int* tries)
{
if (guess < tal)
{
(*tries)++;
printf("\nYour guess is too low, try again!");
}
else if (guess > tal)
{
(*tries)++;
printf("\nYour guess is too high, try again!");
}
else if (guess == tal)
{
(*tries)++;
printf("\nCongratulations, that is correct!");
printf("\nYou made %d attempt(s)", *tries);
}
}
int main (void)
{
int tal; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char playAgain;
do {
srand(time(NULL));
tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
printf("\nIm thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
talfunktion(tal, guess, &tries);
printf("\nPsst, the right number is: %d", tal); // remove later, not relevant to uppg.
getchar(); //to halt the code for taking the input
if(guess == tal)
{
tries = 0;
printf("\nPlay Again? (y/n)\n");
scanf("%c", &playAgain);
}
} while (playAgain != 'n');
return 0;
}
There are several things mentioned in the comments that describe problems,
Things you should look at:
Do not define a function inside another function
be careful where you place return statements
when using character testing, use char type for variable
consider simplifying your logical comparisons. (eg guess > tal || guess < tal is the same as guess != tal )
make sure automatic variables are placed such that they are visible where used.
Place space in format specifier: " %c" for scanf() to consume newline character. (instead of excessive use of getchar())
Here is a simplified version of your code, with modified main and talfunktion functions...
char talfunktion(int tal);
int main (void) {
int tal=0;//remove from inside {...} to make it visible to rest of function
char repeat = 'n';
srand(time(NULL));
tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
do {
repeat = talfunktion(tal);
}while((tolower(repeat) == 'y'));
return 0;
}
char talfunktion(int tal)//do all relevant work in function and return
{ //only what is necessary
int guess = 0;
char repeat = 'n';
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter a number from 1 to 100: ");
scanf("%d", &guess);
if((guess < 1) || (guess > 100))
{
printf("Entered out of bounds guess...\n");
}
else if (guess != tal)
{
if(guess < tal) printf("guess too small\n");
else printf("guess too large\n");
printf("Try again? <'n' or 'y'>\n");
scanf(" %c", &repeat);//space in format specifier to consume newline character
if(tolower(repeat) != 'y') return 'n';//tolower() allows both upper and lower case
}
else
{
printf("Congratulations: You guessed right.\n");
printf("Play again? <'n' or 'y'>\n");
scanf(" %c", &repeat);
}
return repeat;
}

count value and back again to the beginning of the code when user input numbers

after the program count what use input, it will printout the value, and after it the program will ask to continue or not, and if i press 'Y' the programm will start from the beginning when user input number. the question is how to make the program back to the beginning if user press 'Y'?
#include <stdio.h>
#include <stdlib.h>
void VOne();
int main(void) {
VOne();
return 0;
}
void VOne() {
int i,quiz,exer,test,Final,FV,back;
char again;
while (1) {
printf("Input Value : ");
scanf("%d %d %d %d",&quiz,&exer,&test,&Final );
FV = 0.10+(0.10*quiz)+(0.15*exer)+(0.30*test)+(0.35*Final);
printf("%d\n",FV );
if (FV >= 75) {
printf("You pass the this class\n" );
}
else {
printf("You've to take this class again in the next term\n");
}
printf("You want to input again?\n'Y'or'N\n");
scanf("%c ",&again );
if (again == 'y') {
continue;
}
}
return;
}
This should work.
#include <stdio.h>
#include <stdlib.h>
void VOne();
int main(void) {
VOne();
return 0;
}
void VOne() {
int i,quiz,exer,test,Final,FV,back;
char again;
while (1) {
printf("Input Value : ");
scanf("%d %d %d %d",&quiz,&exer,&test,&Final );
FV = 0.10+(0.10*quiz)+(0.15*exer)+(0.30*test)+(0.35*Final);
printf("%d\n",FV );
if (FV >= 75) {
printf("You pass the this class\n" );
}
else {
printf("You've to take this class again in the next term\n");
}
printf("You want to input again?\n'Y'or'N\n");
scanf(" %c ",&again );
if (again == 'y' || again == 'Y') {
continue;
}
else break;
}
return;
}

Program not returning scanned character

So in my class, part of the homework assignment is to have a function that will return a character that's been entered.
I tried to create this sample code, but it's not working as I hoped.
#include <stdio.h>
char readCharacter();
int main(){
char x;
x = readCharacter();
printf("You inputted %c", x);
return 0;
}
char readCharacter(){
char z;
printf("Input character\n");
scanf("% c", &z);
return z;
}
I enter a character, I decided to type w, and the program told me the character was some weird funky font.
The actual code from my homework, or rather a snippet from it, is
#include <stdio.h> // needed by printf, scanf()
#include <ctype.h> // needed by tolower()
#include <stdlib.h> // for exit()
double readNumber(char *prompt) {
double val;
printf("%s", prompt);
scanf("% lf", &val);
//if input is not a number, exit program
if (scanf("%lf", &val) != 1) {
printf("Invalid input.\n");
exit(1);
}
return val;
}
char readYesOrNo(char* prompt) {
char yn;
printf("%s\n", prompt);
scanf("% c", &yn);
return yn;
}
int main() {
double bonus;
char yesNo;
yesNo = readYesOrNo("Did the worker get a bonus ? (y/n) ");
if (yesNo == 'y' || yesNo == 'Y') {
bonus = readNumber("Enter bonus: ");
}
else {
bonus = 0;
}
return 0;
}
In the actual homework code, the readYesOrNo function doesn't even wait for me to input anything, it just displays the prompt asking for a y/n response, then goes on to the next line of code, not waiting for user input and assuming a no response.
I have no clue why this isn't working.
% c is not a valid format specifier. But %c is probably what you meant.
This line:
scanf("% c", &z);
Needs to be this:
scanf("%c", &z);

Entering a character instead of integer

I'm using a do-while loop to print a menu to the screen. And I'm reading choice as an integer. The proplem is that if the user enter a character the program blows up. How can I avoid that?
#include <stdio.h>
int menu() { // prints the main menu of labs///
int choice;
printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
scanf("%d", &choice);
return choice;
}
int main() {
int choice;
do {
choice = menu();
if (choice != 4) {
if (choice == 1)
//lab5(choice);
else if (choice == 2)
//lab10(choice);
else if (choice == 3)
// lab11(choice);
else
printf("invalid choice\n");
}
} while (choice != 4);
return 0;
}
This should work for you, you need to check the return value of scanf
int menu() { // prints the main menu of labs///
int choice;
printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
if(scanf("%d", &choice) == 1)
{
return choice;
}
else
{
return 0;
}
}
The scanf() (and family of functions) returns the number of successful conversions from the input buffer, if the conversion (%d) fails the function returns 0 (or EOF). In this case the character that could not be converted is not removed from buffer, this is why the endless loop occur, the conversion keeps failing for ever.
I used this method to flush the input buffer after the scanf call and the program behaved as expected.
Run the program online (don't know for how long this will stay up)
void flushInput(){
int c;
while((c = getchar()) != EOF && c != '\n')
/* discard */ ;
}
int menu() { // prints the main menu of labs///
int choice;
printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
if(scanf("%d", &choice) != 1){
flushInput();
return 0;
}else{
flushInput();
return choice;
}
}
/*USE This Code*/
#include <stdio.h>
#include <stdlib.h>
void orderAsk(int orderStorage[1]);
int main()
{
int orderStorage[1];
orderAsk(orderStorage);
printf("%d",orderStorage[0]);
return 0;
}
void orderAsk(int orderStorage[1]){
int d;
d = scanf("%d", &orderStorage[0]);
if ( d!= 1) {
system("cls");
fflush(stdin);
printf("Error! Re-Enter\n");
orderAsk(orderStorage);
}
}

Why does this C loop skip the first attempt to input a letter?

This is a program I am making for a class. It is supposed to read a letter from a file, and then in the game the user tries do guess the letter. with every wrong attempt the program tells you if the actual letter comes before or after your guess in the alphabet.
For some reason when I run it, the loop skips the first attempt in the getLetter function and does not let you input the letter. Why is this?
#include <stdio.h>
#include <ctype.h>
#define MaxGuesses 5
void instructions();
int playGuess (char solution);
char getLetter ();
int compareLetters (char guess, char solution);
int main()
{
int numGames;
int i;
char solution;
char guess;
int result;
FILE *inFile;
inFile=fopen("inputLet.txt","r");
instructions();
scanf("%d", &numGames);
for(i=1; i<=numGames; i++)
{
printf ("\nThis is game %d\n", i);
fscanf(inFile, " %c", &solution);
result = playGuess(solution);
if (result == 1)
printf("You've WON!\n");
else
printf("You've LOST :(\n");
}
//close file
fclose(inFile);
return 0;
}
void instructions ()
{
printf ("This game consists of guessing letters.\nThe user will have up to 5 chances of guessing correctly,\nupon every failed attempt,\na hint will be provided regarding alphabetical position.\n\nEnter the number of games you wish to play (max 4): ");
}
char getLetter()
{
char userGuess;
printf("\nPlease enter your guess: ");
scanf("%c", &userGuess);
userGuess = tolower(userGuess);
return userGuess;
}
int compareLetters(char guess, char solution)
{
if (guess == solution)
return 1;
else if (guess < solution)
{
printf("\nThe letter that you are trying to guess comes before %c", guess);
return 0;
}
else if (guess > solution)
{
printf("\nThe letter that you are trying to guess comes after %c", guess);
return 0;
}
}
int playGuess (char solution)
{
int numGuesses = 0;
int winOrLose = 0;
char guess;
while(numGuesses < MaxGuesses && winOrLose == 0)
{
guess = getLetter();
winOrLose = compareLetters(guess, solution);
numGuesses++;
}
return winOrLose;
}
It may be consuming a character left in the input buffer (possibly a newline or other whitespace character). You could try changing the format string from "%c" to " %c" as you've done elsewhere, which will skip all the whitespace characters in the buffer before trying to read a character.

Resources