in C programming, how to print 1 character [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've made the following but it skips the part where I have to input the character and I don't understand what my mistake is. Any help ?
#include <stdio.h>
main()
{
int num;
float f;
char c;
printf("Input an integer: ");
scanf_s("%d", &num);
printf("Input an floating point number: ");
scanf_s("%f", &f);
printf("Input a character: ");
scanf_s("%c", &c);
printf("\nThe number is: %d\n",num);
printf("\nThe floating point number is: %f\n", f);
printf("\nThe character is: %c\n", c);
return 0;
}

scanf_s("%d", &d);
This reads characters as long as they fit the "%d" format. The first character not fitting that format is the newline you entered. This remains in the input stream.
scanf_s("%f", &f);
This skips leading whitespaces (i.e., your newline), then reads characters as long as they fit the "%f" format. The first character not fitting that format is the newline you entered. This remains in the input stream.
scanf_s("%c", &c);
This reads one character from the input without skipping potential leading whitespace, i.e., your newline.
It also is undefined behaviour: One thing that scanf_s() does differently than standard scanf() is that it demands a "buffer size" numerical parameter for %c and %s, to avoid buffer overflow. Not giving that parameter makes scanf_s() pull an integer from the stack where you didn't put one, resulting in undefined behaviour. If that next memory address happens to be zero, you'll be scratching your head a lot I would bet...

If I'm not wrong your scanf_s("%c", &c); reads the '\n' character from the previous input.
What you can do is add 1 space before %c so:
scanf_s(" %c", &c);
that will fix your issue. Remember you need to do that if reading a character after some previous input.
Tested and works.

Specify the size. Use this line:
scanf_s("%c", &c, 1);
It should work!

Related

Read user input twice in a for-loop using fgets and scanf [duplicate]

This question already has answers here:
fgets doesn't work after scanf [duplicate]
(7 answers)
Closed 1 year ago.
CODE:
#include<stdio.h>
#include<stdlib.h>
int main(){
struct mobile{
char N[10];
int ram, pixel, price;
}B[5];
int min;
char trash;
for(int i = 0; i < 5; i++){
printf("Enter Mobile Name: ");
fgets(B[i].N, sizeof(B[i].N), stdin);
printf("Enter features (ram/camera pixels/price): ");
scanf("%d%d%d", &B[i].ram, &B[i].pixel, &B[i].price);
printf("\n");
}
}
The program is not accepting value for name of mobile second time. It prints Enter mobile name but don't take value then print Enter features and ask for value. I tried adding a second scanf above printf("\n"); but didn't work. Help please. Thanks.
Remove \n from buffer
scanf leaves a newline in the buffer, which is then read by fgets. The other problem is, that you aren't dividing the user input using a delimiter so I would put a space or a slash between the type specifiers %d:
scanf("%d/%d/%d\n", &B[i].ram, &B[i].pixel, &B[i].price);
The input should then be something like this:
Enter specs (ram/pixels/price): 8/12/500
The trailing character \n is now being read, but it isn't stored in any variable.
Remove \n from fgets() input
This doesn't cause your problem, but I would also remove the trailing \n from the fgets() input, because it's probably not supposed to be part of the phone's name.
#include <string.h>
fgets(B[i].N, sizeof(B[i].N), stdin);
B[i].N[strcspn(B[i].N, "\n")] = '\0';

Why use getchar in specific line? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Why the following code is getting terminated after one round if the getchar() in the 5th line is not used?
char s;
while(1){
printf("Enter two integers: ");
scanf("%d%d",&a,&b);
getchar();
c = a + b;
printf("Addition of %d & %d is %d\n",a,b,c);
printf("Add more numbers(yes/no): ");
scanf("%c",&s);
if(s == 'y')
continue;
else
break;
}
And why using string is not working in the following code? I have included the <string.h> file.
char s[10];
while(1){
printf("Enter two integers: ");
scanf("%d%d",&a,&b);
getchar();
c = a + b;
printf("Addition of %d & %d is %d\n",a,b,c);
printf("Add more numbers(yes/no): ");
scanf("%s",s);
if(s == "yes")
continue;
else
break;
}
When you enter the input for the first scanf("%d%d",&a,&b) then you probably ended that with the Enter key.
That Enter key is added as a newline into the input buffer that scanf reads from.
If you don't have the getchar() call then that newline is what the next scanf("%c",&s) will read.
One solution is, as you've noted, to use getchar() to read and throw away the newline. Another solution is to ask scanf to do the same:
scanf(" %c",&s);
// ^
// Note the space here!
The leading space tells scanf to skip and ignore all leading white-space character, of which newline is one such character.
Note that most format specifiers for scanf automatically skip and ignore leading white-space. For example %s will do that, which means your second version with scanf("%s",s) doesn't need the getchar() call.
Also note that this should have been easily deduced by spending five minutes in a debugger to step through the code statement by statement while monitoring variables and their values.
Then for s == "yes". What happens here is that the array s will decay to a pointer to its first element, as will the literal string, and then you compare these pointers to see if they are the same, which they will most likely never be.
It's somewhat simplified equivalent to this:
char yes_literal[4] = "yes";
if (&s[0] == &yes_literal[0]) ...

How to prompt the user to enter an integer and a character from the keyboard in C [duplicate]

This question already has an answer here:
How to read / parse input in C? The FAQ
(1 answer)
Closed 4 years ago.
I am trying to figure out the best way to get an integer and a character from a user
Here is what I have so far:
#include <stdio.h>
int main()
{
int a;
char b;
printf("enter the first number: \n");
scanf("%d", &a);
printf("enter the second char: \n");
scanf("%c", &b);
printf("Number %d",a);
printf("Char %c",b);
return 0;
}
The output is not shown correctly. Is there any problem with this?
Your input and output statements are fine. Just replace printf("Number %d",a); with printf("Number %d\n",a); to better format the output. Also you should change your second scanf statement to scanf(" %c", &b);. This will deal with the newline character entered after the number is inputted.
After you enter the number, you pressed the Enter key. Since the scanf function works on the input stream, when you try to process the next char after reading the number, you are not reading the character you typed, but the '\n' character preceding that. (i.e. because the Enter key you pressed added a '\n' character to your input stream, before you typed your char)
You should change your second call to scanf with the following.
scanf(" %c", &b);
Notice the added space character in the formatting string. That initial space in the formatting string helps skip any whitespace in between.
Additionally, you may want to add \n at the end of the formatting strings of both printf calls you make, to have a better output formatting.
Here you need to take care of hidden character '\n' , by providing the space before the %c in scanf() function , so the "STDIN" buffer will get cleared and scanf will wait for new character in "STDIN" buffer .
modify this statement in your program : scanf("%c",&b); to scanf(" %c",&b);

scanf() function doesn't work? [duplicate]

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.

Odd loop does not work using %c [duplicate]

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);
}
}

Resources