This question already has answers here:
fgets doesn't work after scanf [duplicate]
(7 answers)
Why does a space in my scanf statement make a difference? [duplicate]
(3 answers)
Closed 5 years ago.
I'm trying to code very simple code, and here it is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int age;
char gender;
printf("How old are you? \n");
scanf("%d", &age);
printf("What is your gender? (m/f) \n");
scanf("%c", &gender);
if ((age >= 18 && gender == 'm')){
printf("You may enter this website ");
if (age <= 20)
{
printf("dude.");
}
}
if ((age >= 18 && gender == 'f')) {
printf("You may enter this website ");
if (age <= 20)
{
printf("young lady.");
}
}
else if (age < 18)
{
printf("Nothing to see here! \n");
}
return 0;
}
In the code above, I'm trying to use a nesting if statement. But it doesn't work, not as I wish. After I enter the age, it prints out the sentence: What is your gender? (m/f).
When the second sentence is printed out, it terminates. But I don't know why.
I want the user be able to enter the gender and based on the entered gender and age it should print out a sentence.
Could you please give me a hint?
There is nothing wrong with the logic of your code, so the most likely reason for the behavior that you see is this line:
scanf("%c", &gender);
Since the line follows reading of an int, the '\n' that remains in the buffer gets assigned to gender immediately.
You can fix this by adding a space in front of %c to ignore newline:
scanf(" %c", &gender);
You can also reduce the code somewhat by combining a few checks:
if (age >= 18){
printf("You may enter this website ");
if (age <= 20) {
printf("%s.\n", gender == 'm' ? "dude" : "young lady");
}
}
Replace scanf("%c", &gender) with scanf(" %c", &gender)
This is because when you enter your age and press enter key, your age will be stored in age variable but '\n'(enter key) is still present in the buffer which will be read by the gender.
So, you can do these things-
scanf("%d\n",&age)
or
use
scanf("%d", &age);
getchar();
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 9 months ago.
#include <stdio.h>
void print_instructions(){
printf("You will need to input a letter to guess,\n");
printf("Then let the player see the screen, and make guesses.\n");
}
int main(){
char input;
print_instructions();
printf("What letter will the player guess? ");
scanf("%c", &input);
printf("The letter is '%c' (ascii %d)\n", input, input);
int asterisk = 1;
while(asterisk <= 10){
printf("*\n");
asterisk++;
}
int attemptNum = 1;
int z;
while(attemptNum <= 10){
char guess;
printf("What is guess #%d? ", attemptNum);
scanf("%c", &guess);
if(guess <= 96){
printf("Your guess must be a valid letter!\n");
}
else if(guess < input){
printf("Not quite! Guess later in the alphabet.\n");
}
else if(guess > input){
printf("Not quite! Guess later in the alphabet.\n");
}
else{
printf("Congratulations! You got the letter right!\n");\
break;
}
attemptNum++;
}
}
I think I did nothing wrong using while, but I keep having an error like this:
What did I do wrong?
I have no idea why while repeats itself twice on the odd numbers. Is it something to do with the data structure?
There is no issue with while, but with your scanf - it's reading enter from the buffer that you confirmed input with. try scanning like this to clear the enter
scanf("%c\n", &guess);
Because every time you press the enter button on the keyboard, the enter itself will be also seen as a character \n. Its ASCII code is 10, which is invalid for your condition if(guess<=96). Your problem isn't related with the while loop at all.
To solve this problem:
Use getchar() to "absorb" \n
Use fflush(stdin) to clear all characters remained
I know others have asked similar questions but they are often old posts with outdated code and solutions.
Regardless of whether I use scanf_s or fgets, it always seems to get skipped despite the fact that I have done this the exact same way on other PCs with the same version of VS and they work fine.
int main() {
char name[20];
name[0] = 0;
printf("Enter your name: ");
scanf_s("%[^\n]%*c", &name[0], 20);
printf("\n");
printf("Your name is %s", name);
}
What am I doing wrong that makes this an issue now but not when this is done elsewhere?
EDIT:
After recreating it and only it in another file and seeing a post (and commenting off certain sections and testing it) I now realize that another part of the code is messing with it. Specifically the scanf_s("%d", &age); of the following code:
int main() {
int age;
int ageDifference;
printf("Enter your age: ");
scanf_s("%d", &age);
if (age == 18) {
printf("You are 18 years old.");
}
else if (age > 18) {
ageDifference = age - 18;
printf("It has been %d years since you were 18.", ageDifference);
}
else {
ageDifference = 18 - age;
printf("It will be %d years before you are 18.", ageDifference);
}
printf("\n");
char name[20];
name[0] = 0;
printf("Enter your name: ");
scanf_s("%[^\n]%*c", name, 20);
printf("\n");
printf("Your name is %s", name);
return 0;
}
Screenshot of output: https://prnt.sc/qdo38t
Why is it causing it to skip it though?
Sorry for being such a noob at C too.
FIXED: Adding a space so that scanf_s("%[^\n]%*c", name, 20) is now scanf_s(" %[^\n]", name, 20) fixed it. Also %*c is not needed. Thanks #Weather Vane.
Let us walk through
printf("Enter your age: ");
User input 6 6 Enter
scanf_s("%d", &age);
scanf() reads "66", leaving the '\n' in stdin.
....
printf("Enter your name: ");
scanf_s() attmepts to read the '\n', which does not meet the criteria of "%[^\n]", so scanf_s() stops right away and does not return a 1 - still leaving the '\n' in stdin.
scanf_s("%[^\n]%*c", name, 20)
Code did not check scanf_s() results, Tsk, tsk, and so does not know that name[] remains unchanged.
Using a space as in " %[^\n]%*c" helps, to first consume the left-over '\n', but the best advice is to not use scanf(), scanf_s() at all. Use fgets() to read a line into a string and then parse the string with sscanf(), strtol(), etc.
In all cases, check the return value of input functions.
I have written this simple program, which is supposed to calculate the factorial of a number entered by the user. The program should ask the user to stop or continue the program in order to find the factorial of a new number.
since most of the time user don't pay attention to CapsLock the program should accept Y or y as an answer for yes. But every time I run this program and even though I enter Y/y , it gets terminated !
I googled and found out the problem could be due to new linecharacter getting accepted with my character input so, I modified the scanf code from scanf("%c", &choice); to scanf("%c ", &choice); in order to accommodate the new line character , but my program is still getting terminated after accepting Y/y as input.
Here is the code . Please if possible let me know the best practices and methods to deal with these kinds of issues along with the required correction.
#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)
void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program
do {//Makes sure the loop isn't terminated until the user decides
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);
if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;
i--;
}
}
printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result
printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);
} while (choice =="y" || choice =="Y"); // Checks if user wants to continue
}
I'm a beginner in programming and I'm running this code in visual studio 2015.
Just modify your scanf like following:
printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after
also you should use:
} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue
NOTE:
Simple quote ' is used for characters and double quote " is used for string
Your second-last line has a string literal "y", which should be a character literal i.e. 'y':
} while (choice =="y" || choice =="Y");
This should be:
} while (choice =='y' || choice =='Y');
Also, your scanf() doesn't consume whitespace. Add a space before %c to make it ignore newlines or other spaces:
scanf(" %c", &choice);
Try doing the following even after the correction there are still some bugs in the code
In your code if you type 'Y' and recalculate a factorial it gives wrong answer as
int factorial is already loaded with the previous value
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace System;
using namespace std;
int calculateFactorial(int i);
int main()
{
int i;
char choice;
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
printf("\n The factorial of entered no is :\t %d", calculateFactorial(i));
printf("\n Do you want to continue (Y/N)?");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}
int calculateFactorial(int i) {
int factorial = 1;
if (i == 0){
factorial = 1;
}else {
while (i > 0){
factorial = factorial*i;
i--;
}
}
return factorial;
}
Basically I'm a beginner coder and this is what I wrote:
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("COLOR 0A");
char playerName[13];
char playerGender;
int playerAge;
printf("Please input your name and age!\nName: ");
scanf("%s", playerName);
printf("Age (from 18 to 50): ");
scanf("%d", &playerAge);
label:
if(playerAge > 18 && playerAge < 50)
{
printf("What gender are you, M(male) or F(female): ");
scanf("%c", playerGender);
gender:
if(playerGender == 'M' || playerGender == 'F'){
printf("Okay, so your name is %s, you're %d years old and you're a %s.", playerName, playerAge, playerGender);
}else{
printf("Try again.\n\n"
"What gender are you, M(male) or F(female): ");
scanf("%c", playerGender);
goto gender;
}
}else{
printf("Wrong, try again.\n"
"Age (from 18 to 50): ");
scanf("%d", &playerAge);
goto label;
}
return 0;
}
When I put the required age to continue, it crashes on the scanf for the playerGender. Right after it shows me the question about my gender? Where is my mistake?
try:
scanf("%c", &playerGender);
instead of
scanf("%c", playerGender);
as scanf takes a pointer and not a reference to the variable you are trying to fill.
I am also beginner but I think that you need to write thisscanf("%s", playerName); like thisscanf("%12s", playerName);
BTW let me know if that works.
Below is a simple program that the user enters the number of subjects taken --> the grade (A,B,C etc.) --> and the program calculates and prints the students transcript including all the cgpa.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char string[10];
char grade[10];
float out[10];
int num;
float cgpa=0.0;
for(int x=0;x<num;x++)
{
printf("\nEnter the number of subjects? \n ");
scanf("%d",&num);
printf("\nEnter Student Name: \n");
scanf("%s",&string[x]);
printf("\nEnter Student Grade: \n");
scanf("%s",&grade[x]);
if(grade[x]>="A" || grade[x]>="a")
out[x]==4.0;
else if(grade[x]>="B" || grade[x]>="b")
out[x]==3.0;
else if(grade[x]>="C" || grade[x]>="c")
out[x]==2.0;
else if(grade[x]>="D" || grade[x]>="d")
out[x]==1.3;
else if(grade[x]>="F" || grade[x]>="f")
out[x]==0.1;
else
printf("You've entered a wrong grade");
}
cgpa+=out;
cgpa=cgpa/num;
printf("%s\n", string);
printf("%s\n", grade);
printf("%f\n", cgpa);
getch();
}
My main problem is that I keep on getting the two following errors:
Cannot convert char to char*
illegal use of floating point
The errors I'm getting are on the following lines:
if(grade[x]>="A" || grade[x]>="a")
out[x]==4.0;
else if(grade[x]>="B" || grade[x]>="b")
out[x]==3.0;
else if(grade[x]>="C" || grade[x]>="c")
out[x]==2.0;
else if(grade[x]>="D" || grade[x]>="d")
out[x]==1.3;
else if(grade[x]>="F" || grade[x]>="f")
out[x]==0.1;
The illegal use of floating point error is on this line:
cgpa+=out;
Please see solution. Your original solution had a lot of issues and is fundamentally flawed. The above commentary highlight most of the mistakes you've made, but the main flaw with your original solution was the lack of clear process structure.
Recommend drafting out your algorithm or process flow before you begin coding in future
1. Grab user input for student name and number of subjects
2. For every subject
a. Get user to input grade
b. Check grade is valid
c. Add to cumulative GPA value
Until num_subjects is met
3. Print out Student Name, Num Subjects and his GPA (cgpa/num_subjects)
See sample solution below, which adheres to the process I defined above.
I hope this assists you in your programming journey :)
#include <stdio.h>
// #include <conio.h> - Commented this out because this is MS Dos specific and makes solution non portable
#include <ctype.h>
int main(void)
{
int num_subjects;
char name[10];
char grade;
float cgpa=0.0;
int x;
// These do not need to be within your loop. Especially num_subjects
printf("\nEnter Student Name: \n");
scanf("%s", &name[0]);
printf("\nEnter the number of subjects? \n ");
scanf("%d", &num_subjects);
// I've replaced this with a while loop, because you need a continuous loop until a valid grade is required
while( x < num_subjects )
{
printf("\nEnter Student Grade: \n");
scanf("%c", &grade);
// Upper case the value, so there is no ambiguity in 'a' or 'A'
grade = toupper(grade);
printf("\nGrade Entered: %c\n", grade);
if (grade == 'A') {
cgpa+=4.0;
}
else if (grade == 'B') {
cgpa+=3.0;
}
else if (grade == 'C') {
cgpa+=2.0;
}
else if (grade == 'D') {
cgpa+=1.3;
}
else if (grade == 'F') {
cgpa+=0.1;
}
else {
printf("You've entered a wrong grade");
// Being lazy here. I'm decrementing the counter, because I am lazy.
// By right, the efficient thing to do is to increment the counter on a valid value
// But in the interest of writing less code, I've decided to decrement the value on an invalid value.
// And add more comments :P
x--;
}
// Increment x if a valid grade was entered.
x++;
}
// Final output line
printf("\nStudent: %s, Number Subjects: %d, GPA: %.2f", name, num_subjects, cgpa/num_subjects);
}
You can't add a whole array to a floating point number.
And grade [x] is a char while "A" is a char array.
Also you have to scanf your number before using it in your for loop.
Change this:
if(grade[x]>="A" || grade[x]>="a")
out[x]==4.0;
For this:
if(grade[x]>='A' || grade[x]>='a')
out[x]=4.0;
Why?
reason 1: grade is an array of characters, not strings.
reason 2: == is a boolean operator (like the >= in your example). To set a variable value use just =
Study a little before coding. It is a very basic question.