scanf seems to break my code (C programming) [duplicate] - c

This question already has answers here:
C/C++ printf() before scanf() issue
(2 answers)
Closed 1 year ago.
I'm programming a text-based adventure game for my C Programming class, but for whatever reason, the code seems to break whenever I try to use "scanf" to get a player's input. Everything will print onto the console perfectly fine, but then when I include the line "scanf("%d", playerInput), nothing will print out and the program will run endlessly. Anyone know why this is the case? Here's my code:
#include <stdbool.h>
#include <stdio.h>
int main()
{
printf("~ Doctor Crowley: Master of Death ~\n"); //Titlecard
//Introductory narration =================================================================================================
printf("\n- Narrator -\n");
printf("You are Doctor Jonathan Crowley, an archeologist and wizard from the Arcane University in Aeternum.\n");
printf("You awaken in your classroom on the first floor of the University. Last you remember, you were in your office\n");
printf("on the sixth floor of the University.\n");
// Player Actions (1) ========================================================================================================================
printf("\n1. Stand up\n");
printf("2. Look around\n");
printf("-------------------------------------------\n");
int playerInput; //player input variable
printf("--> ");
scanf("%d", &playerInput);
return 0;
}

First of all make sure to write '&' before any variable in scanf. If you don't write that, it will crash and force you to end the program. Then as you write in your code it just input number and will put that in variable playerInput, and nothing more. You didn't print anything after scanf, so nothing will happen after that. For example you can write printf("%d",playerInput); after that and it will print the number that is in playerInput.

Related

Code not asking for second %c input and just prints [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 10 months ago.
My code isn't asking for the second %c input and just printing the result. of the first and printing the next question after.
This is the assignment: Students can take Programming module if they are from SOE or they have passed Math. Otherwise, they cannot take the module.
Write a program to allow students to check their eligibility. Your program must have only one if-else statement and must use the OR logical operator in the condition.
Your program must be able to produce the sample outputs given below. Note that the values underlined are the input data.
this is the code i wrote:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char soe, math;
printf("Are you from SOE [y/n]? ");
scanf("%c", &soe);
printf("Did you pass Math [y/n]? ");
scanf("%c", &math);
if(soe == 'y' || math == 'y'){
printf("OK, you can take Programming");
}
else{
printf("Sorry, you cannot take Programming");
}
}
Are you from SOE [y/n]? y
Did you pass Math [y/n]? OK, you can take Programming
it immediately prints the 2nd printf after the 1st input and doesnt ask for a second input
You have to use getchar() between two scanf function calls, unless they are using the %d conversion format specifier.
(This function cleans the buffer by consuming the ENTER key that you pressed after the first scanf. If you don't do it, the ENTER key still exists and the next scanf will take it as an answer.)
This way :
printf("Are you from SOE [y/n]? ");
scanf("%c", &soe);
getchar();
printf("Did you pass Math [y/n]? ");
scanf("%c", &math);

how to error check when using scanf_s to take only integers? [duplicate]

This question already has answers here:
C programming - Loop until user inputs number scanf
(4 answers)
Closed 4 years ago.
edit1:
Sorry, I am in an intro to programming class... I read the two links, but don't fully understand them...
I tried to to add
if (scanf_s("%d", &input) == 0) {
fflush(stdin);
continue;
}
but that didn't seem to do anything. I understand that scanf is in an error state, so it will refuse to run, and that I need to clear a buffer of the bad input from user.
so basically, I am looking for a beginner's solution, for someone who just learned about loops, input/output, and basic error check.
~~~~~~~~~
I am new to C and have a small question. I want to read a list of integers from the console. It works fine if the user does indeed input integers, but if it types something like "acdb", or "0.5", I just get the program printing "enter a number: " infinitely, as if it's running the loop but scanf_s is broken and so it just skips itself.
Thanks for your help.
int input = 1;
while (input != 0) {
printf("enter a number: \n");
scanf_s("%d", &input);
/* rest of code omitted */
}
scanf_s returns the number of variables in the variable argument list that were successfully filled with data.
In your case you want that to be 1 therefore.
If you do encounter invalid input then it's your job to clear that, otherwise it remains on the input stream. For more on that see How to clear input buffer in C?

'C for Dummies' getchar() function not working

I'm currently in the very early stages of learning C programming and am working my way through "Beginning Programming with C for Dummies" using Code::Blocks.
The first activity in Chapter 7, Fetching characters with getchar(), asks us to copy the code exactly as it's presented in the book; see below:
#include <stdio.h>
int main()
{
int c;
printf("I'm waiting for a character: ");
c = getchar();
printf("I waited for the '%c' character.\n", c);
return (0);
}
The output I get is:
I'm waiting for a character:
However according to the book, the output that I should be seeing is the character's ASCII code value. It then asks that I change the %c placeholder to %d to display the value, but still I get the same outcome as before. I could probably recite the code with my eyes closed I've checked it through that may times; I simply cannot see where I'm going wrong.
Am I right in thinking that the getchar() function isn't being recognized? Or that the code isn't being read after the first printf statement? Any guidance is welcome as I don't want to move on until I've understood the problem.
Please enter any key, then 2nd printf will show the result. getchar() is expecting input from user, controller reach at 2nd line & waiting for input.

Unable to execute a do-while loop completely [duplicate]

This question already has answers here:
Yes/No loop in C
(3 answers)
Closed 8 years ago.
I am trying to execute a small program using do-while.
#include<stdio.h>
#include<conio.h>
void main()
{
char another;
int num;
do
{
printf("Enter a number");
scanf("%d",&num);
printf("Square of %d id %d",num,num*num);
printf("Want to another another number y/n");
scanf("%c",&another);
}while(another=='y');
}
Now when I try to execute the program, it runs fine. I input a number and it displays its square. And then I see Want to enter another number y/n. But as soon as I press any key (y or n), the program exits itself before I can press enter to provide the input. I tried it many times but no success.
But the program runs fine if I ask the user to input either 1 or 2(in place of y/n). In that case it takes an integer input and can check the while block. If another == 1, the program runs again.
My problem is that why can't I check for a character in the while condition.
The reason it doesn't work is that after scanf gets num, the new line is still in the buffer, so it will be processed by the next scanf with %c format specifier. A direct way of fixing it is to use:
scanf(" %c", &another);
// ^space
Note that your original scanf("%c:,&another); won't compile, but I assume that's a typo. And always use int main, or it's undefined behavior.

C Programming in Xcode, scanf doesn't read int

I'm practicing C programming language before jump to objective-c, so I'm using the last version of XCode 4.6.3 (I believe this is the last version).
I want to read an input, a numeric input (age), and show the dog age of a person.
Here is my code
#include <stdio.h>
int main()
{
int age;
printf("How old are you? \n");
scanf("%d",&age);
age = age *7;
printf(\nIn dog years you are %d years old",age);
return 0;
}
so i enter my age and it doesn't show the result, sry for the newb question but I've already asked 4 people from work and nothing :(
Thanks!
The Answer!
I don't know why this happens, but I solved it (kind of fun hahahaha). I'm using apple keyboard and the NumLock ENter key doesn't work for debugg o.O . When I use the main Enter key, it works! Thanks everyone =)
This often happens because the program exits before the output buffer gets a chance to empty itself onto the console. Adding \n to the end of printf's format line should fix this problem:
printf("\nIn dog years you are %d years old\n",age);
Printing \n to an output stream which is connected to console "flushes" the output unless you change this setting in your program.
Note: C provides a shorter way of multiplying by 7: instead of
age = age * 7;
you can write
age *= 7;
I think you're missing a quote here:
printf(\nIn dog years you are %d years old",age);
Change it to:
printf("\nIn dog years you are %d years old",age);
I don't know how this is even compiling for you. You are probably getting compile time errors. Remember to compile your code first, then run. When it runs, remember to enter your input in the console, then hit the ENTER key.
I just tried this and it works for me: http://ideone.com/NFU2Ry

Resources