I'm fairly competent with if/else statements, and this is a really old assignment that I ended up turning in partially complete. But I still wanted to know exactly why my code wouldn't work.
I want my user to input name, height, and sex. My code will then display an entire sentence that says "Name is X cm tall and is a male" or "Name is X cm tall and is a female."
When I input name and enter, it immediately then skips displays both the height AND the sex. Regardless of what I input after that, it then ends the program.
Input name: Jack
Input height in cm: 180
sex(M/F):
Computer $
I've been playing around with this code for a while now, but I have been stuck for a while now. Any help would be greatly appreciated. Here is my code:
#include<stdio.h>
int main() {
char name[30];
char sex;
float height;
printf("Input name: ");
scanf("%s", name);
fflush(stdin);
printf("Input height in cm: ");
scanf("%f", &height);
fflush(stdin);
printf("sex(M/F): ");
scanf("%c", &sex);
if (sex == 'M')
{
printf("%s is %f cm tall and male", name, height);
}
else if (sex == 'F')
{
printf("%s is %f cm tall and female", name, height);
}
printf("\n");
return 0;
}
From what I can see it only skips the sex part - which is very sad to be honest :-)).
it immediately then skips displays both the height AND the sex
Input name: Jack Input height in cm: 180 sex(M/F): Computer $
You can try this:
scanf(" %c", &sex);
^
The space causes scanf to eat blanks before reading a character.
fflush(stdin) is a very bad idea (undefined behavior). You should replace this call with an other function call, for example this one :
static void
clean_stdin(void)
{
int c;
do {
c = getchar();
} while (c != '\n' && c != EOF);
}
With it, it seems working.
You're missing an ampersand on line 9:
scanf("%s", name);
shoul be:
scanf("%s", &name);
maybe this helps
You can also try this
printf("sex(M/F): ");
scanf("%s", &sex);
To read a single character from stdin you have to use getchar() instead of scanf("%c", &c)
Or change the variable type of sex to char[2] and use scanf("%s", sex)
Related
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.
This program is supposed to balance an account by asking for original amount then asking what sort of transaction they would like. The printf call is called twice when all I want is one. output: "Enter transaction: Enter transaction: ". Otherwise works fine. code:
#include <stdio.h>
int main(void)
{
float amount, old, new;
char letter;
printf("Please enter your current balance: ");
scanf("%f", &old);
printf("Enter the kind of transaction you would like: W - withdrawl, D - deposit, F - finished. \n");
scanf("%c", &letter);
while (letter != 'F'){
if (letter == 'D'){
printf("Amount: ");
scanf("%f", &amount);
new = old + amount;
old = new;
}
if (letter == 'W'){
printf("Amount: ");
scanf("%f", &amount);
new = old - amount;
old = new;
}
printf("Enter transaction: ");
scanf("%c", &letter);
}
if (letter == 'F')
printf("Your ending balance is %f.\n", old);
return 0;
}
Would greatly appreciate any insight! Thank you!!
scanf(" %c", &letter); instead of scanf("%c", &letter);
the original (without space) would interpret Enter as an input.
You may also be able to solve the issue by clearing the input (previous Enter press) from stdin input buffer. Add this line
fflush(stdin);
before
scanf("%c", &letter);
However, the solution provided by #artm is recommended, mine might not work depending on platform.
Hello i am beginner in programmin. I have simple issue. When i take user input. I was asked
Enter Your Age:
then after entering age i was asked(problem is here: why it's executing two linesc)
"Enter c for city and v for village: Enter 'h' for healthy and 'p' for poor health: "
and cursor comes after health:
It should ask for "Enter c for city and v for village:" first. I have tried alot. Please help me
int main(){
int age;
char sex;
char location;
char health;
printf("Enter Your Age: ");
scanf("%d",&age);
printf("Enter c for city and v for village: ");
scanf("%c", &location);
printf("Enter 'h' for healthy and 'p' for poor health: ");
scanf("%c", &health);
printf("Enter 'm' for male and 'f' for female: ");
scanf("%c", &sex);
if(age>=25 && age<=35){
printf("hello ahmed ");
}
else{
printf("Sorry You Cannot Be Insured ");
}
getch();
return 0;
}
It seems when you enter your age, the 'enter' remains in the buffer and gets read into location.
printf("Enter Your Age: ");
scanf("%d",&age);
printf("Enter c for city and v for village: ");
scanf("\n%c", &location); // add this line to ignore the newline character.
EDIT: fflush() removed because it seems it works only for output streams and not input. IMO Better is to first read the newline character and then the actual location character.
Another option is to
scanf(" %c", &location);
include a space before the %c for it to ignore the white space or new line.
This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 9 years ago.
I have written a simple program to exchange currency and able to buy a beer.
But there something in program and I don't know why, it auto skips the third input data -> end program.
Here my code :
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ex_rate_into_vnd = 20000; //! Exchange Rate
int beer = 7000; //! Local price of a beer
float in_c = 0; //! Input amount of money
float out_c = 2; //! Amount of currency to exchange !
float choice; //! Switch mode
char buy; //! Deal or not
//! Introduction
printf ("||---------------------------------------------------||\n");
printf ("|| Currency Exchange Machine beta ||\n");
printf ("||---------------------------------------------------||\n");
printf ("Please choose your option:\n");
printf("\t 1.Exchange VND to dollar\n");
printf("\t 2.Exchange Dollar to VND\n");
do
{
printf("Your choice: ",choice);
scanf("%f",&choice);
} while( choice != 1 && choice != 2);
printf ("Please enter amount of money:");
scanf("%f",&in_c);
if (choice == 1 )
{
out_c = in_c / ex_rate_into_vnd;
printf ("Your amount of money: %.2f",out_c);
}
else
{
out_c = in_c * ex_rate_into_vnd;
printf ("Your amount of money: %.0f",out_c);
}
//! End of Exchanging
printf ("\nWould you like to buy a beer (y/n) ?",buy);
scanf("%c", &buy);
if (buy == 'y')
{
if (out_c >= 7000)
{
out_c = out_c - 7000;
printf("Transactions success !\n");
printf("Your amount: %2.f",out_c);
}
}
printf ("\nWhy Stop ?");
return 0;
}
You have at least one \n between the latest float entry and the char you want to read. You need to get rid of that first.
See also all answers in getchar after scanf category
Change
scanf("%c", &buy);
to
scanf(" %c", &buy);
// ^space
Because the newline character is still in the input buffer after you enter a number and press ENTER in the second scanf.
Instead of scanf("%c", &buy);
1.use space before %c
scanf(" %c",&buy); //space before %c
^
this skips reading of white space (including newlines).
2.or Use getchar(); before scanf("%c", &buy); statement
getchar(); //this hold the newline
scanf("%c", &buy);
3.or use two times getchar();
getchar();
buy=getchar();
//here getchar returns int , it would be better if you declare buy with integer type.
In GCC usage of fflush(stdin); is discouaraged. please avoid using it.
I was wondering why you made 'choice' a float, not an int
Also, consider using a switch-case
that way, you won't have to do the whole do-while loop.
Also, in the line
printf ("\nWould you like to buy a beer (y/n) ?",buy);
Why did u add that?
Here is what I would have done :
printf("Your choice?\n>");
scanf("%d", &choice);
switch(choice)
{
case 1 :
{
out_c = in_c / ex_rate_into_vnd;
printf ("Your amount of money: %.2f",out_c);
}
case 2:
{
out_c = in_c * ex_rate_into_vnd;
printf ("Your amount of money: %.0f",out_c);
}
default :
printf("\nThere has been an error\n"):
reloadprogram(); /* Reloadprogram() is simply to make this go back to the asking thing :) */
}
}
EDIT: also, where it says if( <somevariable> >= 7000), change 7000 to beer, so that way, if u change beer, you won't have to change this :)
Put a fflush(stdin) to clear the input before the last scanf
The program doesn't skip the third input data, it just scans the newline you press after the second input. To fix this, type scanf("%*c%c", &buy); instead of scanf("%c", &buy);. This little %*c scans and ignores the the character read from the input.
you can remove the buy variable from the printf call, it's unneeded
printf ("\nWould you like to buy a beer (y/n) ?",buy);
And replace char buy by char buy[2]; . because a sting is always terminated by /0.
You can also add a memset (buy, 0, sizeof(buy)), to be sure that memory is reset before you start to use it.
This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 8 years ago.
#include "stdio.h"
int main(void)
{
int order, nextp, N=3;
char cont;
nextp = 0;
printf("\nShould we continue (y or n): ");
scanf("%c", &cont);
if (cont != 'y') return;
for(; nextp < N; nextp++)
{
printf("Enter order number: ");
scanf("%d", &order);
printf("you have entered %d\n", order);
printf("okay now continue with cont\n");
printf("enter cont y or n: ");
scanf("%c", &cont);
if (cont != 'y')
{
printf("\nnot equal to y\n");
break;
}
printf("after intepreting t[0]");
}
return 0;
}
The output looks like this
Should we continue (y or n): y
Enter order number: 45
you have entered 45
okay now continue with cont
enter cont y or n:
not equal to y
The second input was skipped. Why?
because of newline character already in stdin , this is happening.
use
scanf(" %c", &cont);
instead of
scanf("%c", &cont);
note one space before %c.
After scanf("%d", &order); consumes the number (45 in this case), there is still a newline left after that. You can use scanf("%d\n", &order) to make it consume the return.
Another answer to this can be found here:
scanf() leaves the new line char in buffer?
This is why scanf is not typically preferred for character input. There's a left over carriage return after the previous input.
For example, if you were to add a getchar() after the order input, your problem would be solved, but that's not clean code. You can also see this explicitly by subsituting cont != 'y' to cont != '\n'.
Instead, use getchar() for all your input and check for \n
For most conversions scanf will skip whitespace, but for char format ("%c") you must skip white space by using an explicit space in the format (" %c") as explained here:
C - trying to read a single char
This is also explained in the scanf documentation, but it's confusing and may be better to use something else as others have mentioned.
You can use fflush()
printf("enter cont y or n: ");
fflush(stdin);
scanf("%c", &cont);