Program not returning scanned character - c

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);

Related

How to prevent '\n' being passed as input?

When we execute the following code:
#include <stdio.h>
int main(void){
char x,y;
scanf("%c", &y);
x = getchar();
putchar(x);
return 0;
}
The enter that is being inputted in the scanf("%c", &y); statement is passed on to x. Is there some way to get away with this? I now that if we are using scanf then we can ignore the \n by scanf("%*c%c", &x); but don't know what do while using getchar().
You can do something like this
#include <stdio.h>
int main(void)
{
char x,y,ch;
scanf("%c%*c", &y);
while((ch=getchar())!='\n'&&ch!=EOF); //removes all character in input buffer
x = getchar();
putchar(x);
return 0;
}
It's basically the problem of the input buffer, In your case, you can use alternative input-string getchar() with fflush(stdin); for handling this issue.

how to check if user input is a certain character

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 ==.

Why procedure if in C doesn't work with char

I am writing a simple quiz in C (using CodeBlocks 13.12)
It compiles, but doesn't work in second question. Whatever I will input, it always give answer 'that's sad'.
I can't understand what is wrong.
I came to this, where if I comment line 13 ( scanf("%d", &age); ) it's starting works ok for second question.
What the problem is?
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <clocale>
int main()
{
int age;
char S1;
printf("How old is your dog? \n");
scanf("%d", &age);
if (age <= 7)
{
printf(" very young. the end \n");
return 0;
}
else
{
printf("old dog. \n \n");
}
//question2
printf("Do you like dogs? y/n \n");
scanf("%c%c", &S1);
if (S1 == 'y')
{
printf("hey, that's nice \n");
}
else
{
printf(" that's sad :( . \n");
return 0;
}
return 0;
}
You cause undefined behavior by
scanf("%c%c", &S1);
scanf reads two chars, one stored in S1, one stored in some location on the stack because scanf expects a second char* to be supplied.
If your intention is to ignore the newline following the actual character, write
scanf("%c%*c", &S1);
Change the second scanf() to
scanf(" %c", &S1);
This would escape the left out newline character \n in the input buffer.
Plus, you are reading one char in this. So you need only one %c
scanf("%c", &S1);
is the correct way to input one character ,

How to stop a program based on user's input in C

I'm just starting to learn C and I'm having problem with stopping my program based on what the user inputted.
#include <stdio.h>
#include <stdbool.h>
int main()
{
int a;
int b;
char c[5];
printf("Enter the two values you like to compare, type stop to end.\n");
while (c != "stop")
{
scanf_s(" %d %d %s", &a, &b, &c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
printf("Thanks for playing.");
getchar();
return 0;
}
The problem that I'm having is having to put in another variable, c, in my scanf_s. How would I do it so that the user does not have to put in another word after the 2 numbers? Also how can I check if the user only input "stop" so that it will stop the program? Btw the way I have it right now also does not stop the program when I do "10 10 stop". Thanks.
remove & for c in scanf_s(" %d %d %s", &a, &b, &c);
use strcmp to compare strings.
if you need to ignore case while comparing use strcasecmp (for UNIX based systems) and stricmp (for windows).
Use do-while instead of while if you need to run the loop at least once.
Full Working Code:
#include <stdio.h>
#include <string.h>
int main()
{
int a;
int b;
char c[5] = {'\0'};
do {
printf("Enter the two values you like to compare, type stop to end.\n");
scanf("%d%d%s", &a, &b, c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
while (strcmp(c,"stop"));
printf("Thanks for playing.");
getchar();
return 0;
}
while (c != "stop")
You cannot compare strings in C like that, use memcmp() or strncmp() library functions available in string.h. Read about them to know how they can be implemented as condition in while loop.
Also, to get string input, use
scanf_s(" %d %d %s", &a, &b, c); // Remove that litle '&' before 'c'.
NOTE: The function scanf_s returns the number of inputs scanned correctly, you should check that before proceeding with input values.
To get the user to stop without explicitly entering "stop", many ways are there:
1) Use do-while loop and keep asking user if he wants to play more.
2) Use negative numbers input (say -1) to quit.
Use line below to make sure your 'c' scan your string entered.
scanf(" %d %d %s", &a, &b, c);
Edit:
Consider replacing your while with line below to make sure you stop works. Include "string.h"
while (strcmp(c,"stop"))
Here is the fixed version... I have add the comments in the code for understanding...
#include <stdio.h>
#include <string.h>
int main()
{
int a;
int b;
char c[5] = {'\0'};
printf("Enter the two values you like to compare, type stop to end.\n");
while (strcmp(c,"stop"))
{
scanf("%d%d%s", &a, &b, c);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}
printf("Thanks for playing.");
getchar();
return 0;
}
First, lets correct your program:
&c (third argument to scanf_s) is incorrect. It should be c (because it is already a pointer). According to docs, scanf_s requires sizes to be specified for all %s format strings; therefore, the way you are doing things now, you should have written scanf_s(" %d %d %4s", &a, &b, c);
The program would be much easier to use if you changed your logic to "enter a blank line to exit". You can test this looking at the return value of scanf_s, which will be the number of format strings correctly read from the input.
If you need to ask for strings, then allow either, and look at whatever the user wrote to see whether it was number or string:
#include <stdio.h>
#include <string.h>
int main() {
int a;
int b;
char c[32];
printf("Enter the two values to compare, or type stop to end.\n");
while (fgets(c, 31, stdin) != NULL && strncmp("stop\n", c)) != 0) {
// user did not request to exit and wrote something; maybe 2 numbers
if (sscanf(c, "%d %d", &a, &b) != 2) {
// but he did not write two numbers. Complain and repeat.
printf("please write two numbers to compare, or type stop to end.\n");
continue;
}
if (a == b) {
printf("both are equal\n");
} else {
printf("both are not equal\n");
}
}
printf("Thanks for playing.\n");
return 0;
}
fgets reads whole lines, and you can then try to parse them using sscanf. This has the advantage over common scanf that you can try to parse the same line in different ways, depending on what you find in it. Generally, you do not want to fill your code with getchar(). If you are debugging, your debugger will stop for you. If you are not debugging, you will want to test or use your program with input redirection, and getchar() is simply not needed.
Its because you are using &c instead of just c in scanf_s. Replace that and it should work. Also, c is a string, so, you have to use strcmp instead of !=.
An easier way to write this code would be::
int main()
{
int a;
int b;
char c;
do
{
printf("Would you like to play?\nPress 'Y' for 'Yes' or 'N' for 'No'\n");
scanf( "%c", &c ) ;
/*scanf_s( "%c", &c, 1 ) ; */
if( c != 'Y' && c != 'y' )
break ;
printf("Enter the two values you like to compare\n" ) ;
scanf(" %d %d", &a, &b);
if (!(a^b))
{
printf("both are equal\n");
getchar();
}
else
{
printf("both are not equal\n");
getchar();
}
}while(1) ;
printf("Thanks for playing.");
getchar();
return 0;
}

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