This question already has answers here:
How to do scanf for single char in C [duplicate]
(11 answers)
Closed 6 years ago.
Just testing some code; the following is supposed to run until I enter 'n'. But it stops after one round. Can anyone explain it, and help me implement what I want?
#include <stdio.h>
int main ()
{
char another = 'y';
int num;
while ( another == 'y' )
{
printf ("Enter an number ");
scanf ("%d", &num);
printf ("square of %d is %d", num, num * num);
printf ("\nWant to enter another number y/n\n");
scanf ("%c", &another);
}
}
Thanks.
I really appreciate every one's comments. I did search online for GDB, and used it later. I have to say it made identifying the issue so much easier.
Thanks so much.
Add a space before %c
scanf (" %c", &another);
To eat the left out newline in the buffer after the previous scanf().
1) Use the standard definition of main()
int main(void) //if no command line arguments.
2) Do check the return value of scanf() (and other functions), to make sure that the values were read without any errors.
Use
scanf (" %c", &another);
^^^^^
Also it is better to write
printf ("square of %d is %lld", num, ( long long int )num * num);
^^^^ ^^^^^^^^^^^^^^^^^^^^
Related
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 am currently working on a code and I keep having issues with my code. I will add it below, but for some reason, whenever I ask for the input, it skips over the second scanner and goes straight to the third. Does anyone know what the issue may be?
#include <stdio.h>
int main()
{
char a,b,c,d;
printf("Please input the price of your shopping items:");
printf("\n");
printf("Item 1:");
scanf("%c", &a);
printf("Item 2:");
scanf("%c", &b);
printf("\n");
printf("Item 3:");
scanf(" %c", &c);
return 0;
}
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
C skipping one command of a function? [duplicate]
(2 answers)
Closed 6 years ago.
I've been given the pretty simple task of writing a program that will take two characters and then print the letters inbetween them using a for() loop.
Here's my code:
#include <stdio.h>
int main() {
char a, b;
printf("\nEnter the first character: ");
scanf("%c", &a);
printf("\nEnter the second character: ");
scanf("%c", &b);
for(char i = a; i <= b; i++) {
printf("%c ", i);
}
return 0;
}
When I run it, I am prompted to enter the first character correctly but when I press enter it only runs the next printf() and then terminates.
No errors or warnings or anything on compilation. Another similar question I found that was apparently solved does not work for me either.
Thanks in advance.
You have to consume the \n in stdin left by first scanf.
Fastest fix
scanf(" %c", &b);
The space before %c tells to scanf to ignore all whitespaces before to read the char.
If I read your code correctly, by pressing enter, you would enter the second character, which would most probably (depending on the environment) start with a numeric value of 13, which would be smaller than any letter, so the loop's body is executed only once.
This question already has answers here:
Program doesn't wait for user input with scanf("%c",&yn);
(5 answers)
Closed 7 years ago.
I managed to make this simple two part program which consists of simple print and scan functions. The first part is an addition operation and the second part asks the user for a letter and then it repeats it to the user. The first part goes well but when it finishes and is supposed to start the second part it shows the whole thing before I can input a letter.
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int num1, num2 = 522;/*input a number*/ /*add 522*/
int sum; /*sum of num1 and num2*/
char let; /*Letter to put in*/
printf("Hello, my name is John Doe.\n"); /*Print "Hello my name is*/
printf("Please type a number= "); /*Ask user for num1*/
scanf("%d", &num1); /*Scan for num1*/
sum = num1 + 522; /*Add 522 to num1*/
printf("The sum of %d and %d is %d\n", num1, num2, sum);/*print num1 and sum*/
printf("Please type a letter= \n"); /*Ask user for letter*/
scanf("%c", &let); /*Scan for letter*/
printf("You typed %c\n", let); /*Show the letter input*/
return 0;
}
Change
scanf("%c", &let);
to
scanf(" %c", &let);
There is a newline character after a number is entered so that is picked by %c you need to ignore it. Note the space before %c
A better approach is flushing the input buffer after every scanf()/getchar() call.
while ((ch = getchar()) != '\n' && ch != EOF);
but don't use fflush(stdin) because if the file stream is for input use, as stdin is, the behaviour is undefined, therefore it is not acceptable to use fflush() for clearing keyboard input.
As usual, there are some exceptions, check your compiler's documentation to see if it has a (non-portable) method for flushing input.
you can use getchar() function as well to clean the new line character but first method is recommended.
This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 8 years ago.
This may be a simple question, but i searched a lot and still didn't figure it out.
I compiles below snip code by gcc and run program from terminal. In correct, It allow to enter an int and a char but it doesn't. It doesn't wait to enter the char??
Anyone here can help me will be kind. thanks in advance!
#include <stdio.h>
int main()
{
char c;
int i;
// a
printf("i: ");
fflush(stdin); scanf("%d", &i);
// b
printf("c: ");
fflush(stdin); scanf("%c", &c);
return 0;
}
%d will read consecutive digits until it encounters a non-digit. %c reads one character. Probably what's happening is that you're giving it a number (several digits) followed by a new line. %c then reads in that new line. You were probably intending for the fflush(stdin); to discard anything that hadn't yet been read, but unfortunately, that's undefined behavior.
The solution is to discard all whitespace before reading the character:
scanf(" %c", &c);
Note the space at the start. That means to discard all whitespace.
You can use the getchar() to achieve what you want.
or consume the extra newline by using:-
scanf(" %c", &c);
^^^ <------------Note the space
Reason:- Your next scanf for reading the character just reads/consumes the newline and hence never waits for user input
Instead of fflush(stdin); scanf("%c", &c);
1.use scanf with extra space
scanf(" %c",&c);
or
2.use getchar() two times , first time reads '\n' which is entered after giving integer input and second time call ask you for give input as c:
getchar();
c=getchar();
would help you.
First of all, scanf works when used as directed. I think the following code does what you want. Stdout is flushed so that user is prompted to enter an integer or a character. Using %1s allows white space like \n.
int main()
{
char c[2];
int i;
printf("i: ");
fflush(stdout);
scanf("%d", &i);
printf("c: ");
fflush(stdout);
scanf("%1s", &c);
printf("\ni = %d, c = %c", i, c[0]);
return 0;
}
This code was tested/run on an Eclipse/Microsoft C compiler.
That fflush() is not guaranteed to do anything, and gcc/g++ doesn't. Not on Linux, anyway.
I thought I invented the following way to flush the rest of a line...until I saw it as an example in the ISO C spec (90 or 99...forgot which, but it's been there a long time either way...and I'll bet most readers here have seen it before.)
scanf("%*[^\n]%*c"); /* discard everything up to and including the next newline */
You can put that in your own "flush" function to save typing or pasting that all over the place.
You should still follow the suggestions to to put a space in scanf(" %c", &c);.
That will patiently wait for a non-whitespace character in case of a leading space or a double hit of the enter key.
This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 8 years ago.
I am leaning C programming. I have written an odd loop but doesn't work while I use %c in scanf().Here is the code:
#include<stdio.h>
void main()
{
char another='y';
int num;
while ( another =='y')
{
printf("Enter a number:\t");
scanf("%d", &num);
printf("Sqare of %d is : %d", num, num * num);
printf("\nWant to enter another number? y/n");
scanf("%c", &another);
}
}
But if I use %s in this code, for example scanf("%s", &another);, then it works fine.Why does this happen? Any idea?
The %c conversion reads the next single character from input, regardless of what it is. In this case, you've previously read a number using %d. You had to hit the enter key for that number to be read, but you haven't done anything to read the new-line from the input stream. Therefore, when you do the %c conversion, it reads that new-line from the input stream (without waiting for you to actually enter anything, since there's already input waiting to be read).
When you use %s, it skips across any leading white-space to get some character other than white-space. It treats a new-line as white-space, so it implicitly skips across that waiting new-line. Since there's (presumably) nothing else waiting to be read, it proceeds to wait for you to enter something, as you apparently desire.
If you want to use %c for the conversion, you could precede it with a space in the format string, which will also skip across any white-space in the stream.
The ENTER key is lying in the stdin stream, after you enter a number for first scanf %d. This key gets captured by the scanf %c line.
use scanf("%1s",char_array); another=char_array[0];.
use getch() instead of scanf() in this case. Because scanf() expects '\n' but you are accepting only one char at that scanf(). so '\n' given to next scanf() causing confusion.
#include<stdio.h>
void main()
{
char another='y';
int num;
while ( another =='y')
{
printf("Enter a number:\t");
scanf("%d", &num);
printf("Sqare of %d is : %d", num, num * num);
printf("\nWant to enter another number? y/n");
getchar();
scanf("%c", &another);
}
}