scanf and the char variable don't get a long [duplicate] - c

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 6 years ago.
#include <stdio.h>
#include <conio.h>
void main(){
int turn,i=1,num;
char answer;
for(i>0;i++;){
printf("Please enter a number in the range 1-5:");
scanf("%d",&num);
if (num == 1){
printf("Disconnecting\n");
continue;
}
else if(num == 2){
continue;
}
else if(num == 3){
printf("Are you sure you would like to finish your order??? \nplease enter one char:");
scanf("%c", &answer);
if(answer == 'y'){
printf("Canceled");
break;
}
else{
continue;
}
}
else if(num == 4){
turn=i-1;
printf("your position in queue is:%d\n",turn);
continue;
}
else if(num == 5){
break;
}
else {
printf("Wrong input\n");
continue;
}
}
getch();
}
I'm using c language for this,
if You look at the
else if(num == 3)
it should function in a way that when I enter the letter y,Y it will say canceled and end the program and if not it will just reset the loop.
now when I use the number 3 and give the variable c the letter 'y'
it just says nothing and acts like I gave it the command "continue" + pressed the number 3 again although all I have done is press y or Y and enter.
everything else is good.
I would be glad if anyone can tell me how to fix that.

for(i>0;i++;){
printf("Please enter a number in the range 1-5:");
scanf("%d",&num);getchar();
//... rest of your code
}
use getchar or getch to consume extra newline character

The getch found at the bottom of your main is being used to get order numbers.
Try putting a "getch" in right before you are looking for your y character.
That is to say, something like:
else if(num == 3){
printf("Are you sure you would like to finish your order??? \nplease enter one char:");
getch();
scanf("%c", &answer);
if((answer == 'y') || (answer == 'Y')) {
printf("Canceled");
exit;
} else {
continue;
}
}

Related

Fail to ask the user to repeat or exit the program using Do ... While loop in C [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
scanf Getting Skipped [duplicate]
(1 answer)
Closed last year.
I try to make a program that the output will be the classification based on the input grade (by character). Here is my code:
main ()
{
char choice,grade;
printf("Enter a grade: \n");
scanf("%c",&grade);
do
{
if (grade == 'a' or grade == 'A')
{
printf("Excellent!\nDo you want to continue?\n");
}
else if (grade == 'b' or grade == 'B')
{
printf("Good!\n Do you want to continue?\n");
}
else if (grade == 'c' or grade == 'C')
{
printf("Fair!\n Do you want to continue?\n");
}
else if (grade == 'd' or grade == 'D')
{
printf("Average!\n Do you want to continue?\n");
}
else if (grade == 'f' or grade == 'F')
{
printf("Weak!\n Do you want to continue?\n");
}
else
{
printf("Invalid!\n Do you want to continue?\n");
}
scanf("%c",&choice);
} while (choice == 'y');
}
And this is the outcome of the code:
enter image description here
It doesn't allow me to type yes or no. It just ends.
It would be very great if someone explain to me where I'm wrong since this is the first coding language that I learn and I am trying so hard to understand it by myself.
Your scanf() inside the do-while is getting skipped because when you press enter after inputting a grade, scanf() accepts it as a return character. So, do this instead: scanf(" %c", &grade).

How do I reduce multiple outputs

How can I limit the output to only one response when I type in multiple characters.
#include <stdio.h>
main(){
char answer;
printf("Do you want to continue(Y/N)?");
scanf("%c", &answer);
while ((answer != 'Y') && (answer != 'N')){
printf("\nYou must type a Y or an N\n");
printf("Do you want to continue(Y/N) ?");
scanf(" %c", &answer);
}
return 0;
}
Use getchar() for reading the first character, then read next characters until EOF.
Additionaly the reading outside (before) the loop is not necessary.
#include <stdio.h>
// additional function for reading remaining input
void flush();
main(){
// answer needs to be int, because getchar() can return -1 in case of EOF
int answer;
while (1) {
printf("Do you want to continue(Y/N)? ");
answer = getchar();
// read and ignore the remaining input
flush();
if ((answer == 'Y') || (answer == 'N'))
break; // exit loop
printf("\nYou must type a Y or an N\n");
}
// here answer contains 'Y' or 'N'
// do what you need with this...
return 0;
}
// function for consuming the remaining input
void flush()
{
while (getchar() != EOF); // consume input until emptying
}

Scanf in visual studio not accepting multiple cases of characters

I'm creating a conversion project for letters/numbers ASCII table. My code is supposed to be 'interactive', so the user would type 'y' or 'n' to answer questions on the screen. However, it doesn't want to do this twice...
I have tried:
Just trying numbers instead of characters, but it's not exactly what I want
The %[\n]*c, and %[\n]c, and %[\n]*s ... technique but it doesn't help ;-;
Testing in a different project, but the only way I am able to do it is for multiple scanf()s to be in a row.
Here is the code:
printf("Would you like to convert a number today? \n");
printf("Please press Y or N \n");
scanf("%c", &input);
if (input == 'y' || input == 'Y') { //compare input if they said 'yes'
printf("\nThank you! \nWhat number?\n");
scanf("%d", &number);
flag = test(number);
if (flag == 0) { //if there is an equivalent letter
letter = conversion(number); //find the equivalent letter
printf("\nYour Number \t ASCII letter\n");
printf("%d\t %c\n", number, letter);
}
}
else if (input == 'n' || input == 'N') {
printf("\nWould you like to convert a letter instead? This time enter 0 or 1\!\n\n"); //problem here!!
printf("I wish I could say it was to \' Spice things up \' ...but it\'s not ;-; \n\n");
scanf("%d", &input2);
if (input2 == 0) { //this needs to be checking whether the user input Y/y
printf("Great choice adventurer!\n");
printf("What letter will it be today?\n\n");
//..I would go to a different funtion here ie: test2(letter)...
scanf("%d", &number); //I showed that it worked with multiple numbers, but I can't get this to work with multiple letters
printf("%d", number);
}
if (input2 == 1) { //this needs to be checking whether the user input N/n
printf("Difficult to please, I see...\n\n");
printf("I suggest you move on with that attitude!\n\n");
printf("Bye bye then\n");
}
}
else { //if they tried to break the code
printf("Sorry I did not recognise your command...please retry\n");
printf("Press Y or N next time!\n");
}
The first check works perfectly, I just want the second check to be like the first!
Some 'solutions' caused a overflow, which I don't want if possible
Even if someone could explain why this isn't working the way I intended would be very helpful!
I'm not sure what confuses you.
Use
char foo;
scanf(" %c", &foo);
for single characters, eg. letters and
int bar;
scanf("%d", &bar);
for numbers, integers. If you type a letter instead, scanf() will fail.
%[...] is for strings.
scanf() returns the number of successful conversions (or EOF), so for
int height;
int width;
scanf("%d %d", &height, &width);
it returns 2 if successful. It might return 1 if only height could be read.
So to check for errors on user input you should do:
int height;
int width;
if (scanf("%d %d", &height, &width) != 2) {
// handle the error, maybe exit the program.
}
Your code could look like that (without error handling):
#define _CRT_SECURE_NO_WARNINGS // you said Visual Studio? Without it you should get
// warnings about some functions being insecure.
#include <ctype.h> // isalpha() returns true if the value is a letter
#include <stdlib.h> // EXIT_SUCCESS
#include <stdio.h> // puts(), printf(), scanf()
int main(void)
{
for(;;) { // for-ever ... endless loop since the user exits by answering
// 'n' or 'N' two times
puts("Would you like to convert a number today?\nPlease press Y or N:");
char input;
if (scanf(" %c", &input) != 1) // We reached EOF ... end of file
break; // that's improbable for stdin,
// but input could be redirected to
// read from a file instead.
if (input == 'y' || input == 'Y') {
puts("\nThank you!\nWhat number?");
int number;
scanf("%d", &number);
if (isalpha((char unsigned)number)) // *)
printf("\nYour Number \t ASCII letter\n%d\t %c\n\n", number, number);
else
puts("Sorry, but that's not the ASCII code of a letter :(\n");
}
else if (input == 'n' || input == 'N') {
puts("\nWould you like to convert a letter instead?\nPlease press Y or N:");
scanf(" %c", &input);
if (input == 'y' || input == 'Y') {
puts("\nGreat choice adventurer!\nWhat letter will it be today?");
char letter;
scanf(" %c", &letter);
if (isalpha(letter))
printf("\nYour letter \t ASCII code\n%d\t %c\n\n", letter, letter);
else
puts("Sorry, but that's not a letter :(\n");
}
else if (input == 'n' || input == 'N') {
puts("\nDifficult to please, I see...\n\nI suggest you move on with that attitude!\n");
puts("Bye bye then.");
return EXIT_SUCCESS;
}
}
else {
puts("Sorry I did not recognize your command... Please retry.");
puts("Press Y or N next time!\n");
}
}
}
*) isalpha() (and the other functions in <ctype.h>) expects a value that fits in a unsigned char or the value EOF. It has undefined behaviour for other values. Since we read user input into an int we cannot be sure that's the case so we have to cast the value to unsigned char before passing it to isalpha() (and friends).
Next time you ask a question please include your full code, including variable declarations, functions like test() and conversion() and #includes. But please, post an example that focuses on your problem at hand. All that dialog you included would not have been necessary.

Yes & No answer in C

I am trying to make a C program where I can ask the following user yes or no questions:
Do you like beer? Y or N
Are you old enough? Y or N
How old are you?
if the user said over 18 print the message: let's go for some beers
but if one of the 2 first questions or the age is N, print: sorry maybe next time
I think the issue is with the If statement , perhaps I am not encapsulating the conditions.
#include <stdio.h>
int main(){
char answer;
int age = 0 ;
printf("Do you like beers Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n so your answer is %c\n", answer);
printf("Are you old enough to have a beer?\n");
scanf(" %c", &answer);
printf("\n so your answer is %c\n", answer);
if (answer == 'Y') {
printf("how old are you?\n");
scanf(" %d", &age);
if (age >= 18)
printf("\n Let's go for some beers , I will pay the first round \n");
}if else (age < 18 && answer == 'N')
printf("\n sorry my friend , maybe next time \n");
// printf("You may NOT ");
return 0;
}
From your code snippet above, it looks like your else statement is formatted incorrectly (if else instead of else if). Also, since you are testing whether or not either question was false, you should use the || operand. So you would want to do something like:
else if (age < 18 || answer == 'N')
The issue is your last if statement is only true if the user is under 18 AND said No. you want it to be either or.
Change the last if statement from
if else (age < 18 && answer == 'N')
To:
if else (age < 18 || answer == 'N')
You are using the same variable "answer". So, when you enter the answer to the second question it replace the first answer.
int main(){
char answer;
char answer2;
int age = 0 ;
printf("Do you like beers Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n so you answer is %c\n", answer);
printf("Are you older enough to have a beer?\n");
scanf(" %c", &answer2);
printf("\n so you answer is also %c\n", answer2);
if (answer == 'Y' && answer2 == 'Y') {
printf("how old are yo.\n");
scanf(" %d", &age);
if (age >= 18)
printf("\n lets go for some beers , I will paid the first round \n");
}
else if (answer == 'N' || answer2 == 'N')
printf("\n sorry my friend , maybe next time \n");
// printf("You may NOT ");
return 0;
}
Hope this is what you needed. Cheers.
I think that you can think that the structure of your program is roughly as follows.
REPLY = PROMPT(Q1_MESSAGE)
IF(REPLY == YES){
//Narrow down the conditions
REPLY = PROMPT(Q2_MESSAGE)
IF(REPLY == YES){
//Narrow down the conditions
REPLY = PROMPT(Q3_MESSAGE)
IF(REPLY >= 18){
DISPLAY(GOOD_MESSAGE)
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
A nested IF can be considered as AND condition as a condition.
So by summarizing the question message and its response part into a function, it is possible to write as follows.
IF(FUNC1() == TRUE AND FUNC2() == TRUE AND FUNC3() == TRUE){//Function call proceeds from left to right (Shortcut evaluated)
DISPLAY(GOOD_MESSAGE)
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
As an example, you can write concretely as follows.
#include <stdio.h>
int main(void){
char YN(const char *prompt);
int enter_age(const char *prompt);
if(YN("Do you like beers Enter Y or N: \n") == 'Y' &&
YN("Are you old enough to have a beer?\n") == 'Y' &&
enter_age("How old are you?\n") >= 20){
printf("\nLet's go for some beers, I will take the first round.\n");
} else {
printf("\nSorry my friend, maybe next time.\n");
}
return 0;
}
char YN(const char *prompt){
char ans[2], ret, ch;
int ret_scnf;
while(1){
fputs(prompt, stdout);
if((ret_scnf = scanf(" %1[YNyn]%c", ans, &ch)) == 2 && ch == '\n'){
if(*ans == 'Y' || *ans == 'y'){
ret = 'Y';
break;
} else if(*ans == 'N' || *ans == 'n'){
ret = 'N';
break;
}
} else if(ret_scnf == EOF){
ret = 'N';
break;
}
scanf("%*[^\n]");scanf("%*c");//clear input
}
return ret;
}
int enter_age(const char *prompt){
int ret_scnf, age;
char ch;
while(1){
fputs(prompt, stdout);
if((ret_scnf = scanf("%d%c", &age, &ch)) == 2 && ch == '\n'){
if(age < 0)//Can I enter years old at the age of 0?
continue;
return age;
} else if(ret_scnf == EOF){
age = -1;
break;
}
scanf("%*[^\n]");scanf("%*c");
}
return age;
}

scanf char variable in between scanf integer variable doesn't work? [duplicate]

This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 6 years ago.
I thought of making a calculator, just a simple one with loops and the basic operations, but the weird thing is that the scanf of character in between my scanf for number is being ignored. It works fine if I put it on top of the scanf of integer but it wouldn't look anything like a calculator. Is there any way to solve this issue? It's not yet finished; got an error up to here, so wondering what's wrong.
#include <stdio.h>
#include <stdlib.h>
int main(){
int number1,number2,total;
char a;
printf("This is your personal calculator:(End with ""="")\n");
scanf("%d",&number1);
scanf("%c",&a);
scanf("%d",&number2);
if (a == 'x' || a == 'X' || a == '*'){
total=number1*number2;
printf("%d",total);
} else if (a == '/'){
total=number1/number2;
printf("%d",total);
} else if (a == '+'){
total=number1+number2;
printf("%d",total);
} else if (a == '-'){
total=number1-number2;
printf("%d",total);
} else {
printf("error");
}
system("pause");
return 0;
}
You should test that you get a value from scanf(), every time.
The %c character reads the blank or newline after the first number; use " %c" with a leading space to skip over optional white space before reading the character.
if (scanf("%d", &number1) == 1 &&
scanf(" %c", &a) == 1 &&
scanf("%d", &number2) == 1)
{
...process possibly valid input...
}
else
{
...diagnostics...
}
It will probably be easier to give good diagnostics if you read whole lines with fgets() and parse them with sscanf().
Recommendation 1: show an example of what you type as input and what you get as output. This makes it easier for people to help you (they can tell whether the program is producing the same output for them).
Recommendation 2: echo your input so you can see what the program got. This allows you to tell whether the program got the input you expected. You'd probably find that number2 was not containing what you expected, for example.
Recommendation 3: initialize number1 and number2 to -1 so you can see when the scanf() failed (since you aren't yet checking whether scanf() succeeded).
The problem is because of the newline char \n left over by the scanf. This could be avoided by placing a space before format specifier %c.
Try this
scanf(" %c", &a);
^ An space
this will help you to eat up \n char left over by first scanf
int main()
{
int number1,number2,total;
char a;
printf("This is your personal calculator:(End with ""="")\n");
scanf("%d",&number1);
fflush(stdin); // SIMPLE WAY FLUSH THE INPUT STREAM, INPUT BUFFER IS USUALLY CLEARED.
scanf("%c",&a);
scanf("%d",&number2);
if (a == 'x' || a == 'X' || a == '*'){
total=number1*number2;
printf("%d",total);
} else if (a == '/'){
total=number1/number2;
printf("%d",total);
} else if (a == '+'){
total=number1+number2;
printf("%d",total);
} else if (a == '-'){
total=number1-number2;
printf("%d",total);
} else {
printf("error");
}
system("pause");
return 0;
}

Resources