how to use scanf to get input to include space - c

I am new to C this is something I have always been confused about
let's say I have a code like this
I only want to use char
char a, b, c;
printf("input first character: ");
scanf(" %c", &a);
printf("input second character: ");
scanf(" %c", &b);
printf("input thrid character: ");
scanf(" %c", &c);
how ever I want to be able to read in space as well; I noticed how this would only read in non-space characters, what if I want to read space as well something like this c=' '; how do I scan this space in;
now by listening to suggestion of using getchar() I wrote this :
#include<stdio.h>
int main(void)
{
char a,b,c;
printf("input the first char:");
a=getchar();
printf("input the second char:");
b=getchar();
printf("input the third char:");
c=getchar();
return 0;
}
how ever something strange happens when I compile and run the program
the program output is like this
input the first char:
input the second char:input the third char:
now it never let me to input the second char it jumped straight to the third request at the end I was only asked to enter 2 inputs which is very strange because the program clearly asked for 3 in the code.
now here is a program I wrote like this I added what is suggested into the code block
int main(void)
{
int totalHeight=0, floorWidth=0, amountOfStories, amountWindowForTop, amountWindowForMiddle, amountWindowForBottom, windowHeight, middleWindowWidth, topWindowWidth, bottomWindowWidth, minimumHeight, minimumWidth;
int betweenDistanceTop, betweenDistanceMiddle, betweenDistanceBottom, edgeDistanceTop, edgeDistanceBottom, edgeDistanceMiddle;
char topFloorWindowContent, middleFloorWindowContent, bottomFloorWindowContent, windowBorder, floorBorder;
int tempMax, tempValue, tempSideDistance, tempBetweenDistance;
printf("please enter how many stories your building would like to have: ");
scanf("%d",&amountOfStories);
minimumHeight=amountOfStories*6+1;
while((totalHeight<minimumHeight)||((totalHeight%amountOfStories)!=1))
{
printf("please enter the totalHeight (minimum %d): ",minimumHeight);
scanf("%d",&totalHeight);
}
printf("please enter how many window building would have for top floor: ");
scanf("%d",&amountWindowForTop);
printf("please enter how many window building would have for middle floors: ");
scanf("%d",&amountWindowForMiddle);
printf("please enter how many window building would have for bottom floor: ");
scanf("%d",&amountWindowForBottom);
tempMax=amountWindowForTop;
if (tempMax<amountWindowForMiddle)
{
tempMax=amountWindowForMiddle;
}
if (tempMax<amountWindowForBottom)
{
tempMax=amountWindowForBottom;
}
while(floorWidth<tempMax)
{
printf("please enter the width of the building (Minimum %d): ",tempMax*4+1);
scanf("%d",&floorWidth);
}
char a, b, c;
printf("a:");
a=getchar();getchar();
printf("b:");
b=getchar();getchar();
printf("c:");
c=getchar();
printf("a=%c, b=%c, c=%c", a, b, c);
return 0;
}
now here is the funny part if I put this block of code in the big program it doesn't work the output is something like this
please enter how many stories your building would like to have: 2
please enter the totalHeight (minimum 13): 2
please enter the totalHeight (minimum 13): 2
please enter the totalHeight (minimum 13): 13
please enter how many window building would have for top floor: 2
please enter how many window building would have for middle floors: 2
please enter how many window building would have for bottom floor: 2
please enter the width of the building (Minimum 9): 9
a:
b:*
c:a=
, b=
, c=
as we can see a b c all read in \n instead of the space * and c didn't even read anything at all Why is that ?

The problem with your code is this: when you read the first char (a), you press enter (\n) for insert the next char, so now on stdin there is a \n that you haven't readed. When you try to read the next character, (b) the program read the previous \n from stdin and does not allow you to read the next char. So, when you read a char with getchar() and then press enter on the keyboard, you need a second getchar() for remove the \n.
Here is a sample code that could solve your issue:
#include<stdio.h>
int main(void) {
char a, b, c;
printf("a:");
a=getchar();getchar();
printf("b:");
b=getchar();getchar();
printf("c:");
c=getchar();
printf("a=%c, b=%c, c=%c", a, b, c);
return 0;
}
For the edited you posted, you need to put what is called "the stdin cleaner" before taking the value for a,b,c:
while(getchar()!='\n');
it just reomove all characters till \n.
Please, take note that when programs like the one you posted has a lot of input from keyboard, sometime you get this issue because there are extra chars in stdin. So the general answer for this issue will be try to figure out where these extra chars (mostly there is an extra \n somewhere) could be and use a function like the one i mentioned to remove so that you can continue reading from stdin.

You should use getchar()
a = getchar();

scanf will not scan anything until you give any data so it is not useful to scan ' ' char.
for this you have to use getchar() fun for char or gets() for string, it will scan data until you give enter. it will comes out even if either you have not provided any char, or simple ' ' char.

If u want to read the character with space then you may use the gets() functtion.
char str[10];
str=gets();

try scanf("%c", &ch).
as stated in scanf format specifier:
"Whitespace character: the function will read and ignore any whitespace characters encountered before the next non-whitespace character (whitespace characters include spaces, newline and tab characters -- see isspace). A single whitespace in the format string validates any quantity of whitespace characters extracted from the stream (including none)."
getchar() gets unexpected result because in windows, newline(when you hit Enter in console) is two characters.

Related

Why doesn't my program wait for another input?

I've written a small program to practice getting user input using getchar() and outputting it using putchar() in C.
What I want my program to do:
I want the program to ask the user to enter a char, store it in a char variable, and print it out. And then I want it to ask the user to enter another char, store it in another char variable, and print it out.
The following is my code:
#include <stdio.h>
int main()
{
printf("Please enter a char: ");
char myChar = getchar();
printf("The char entered is: ");
putchar(myChar);
printf("\n");
printf("Please enter another char: ");
char myChar2 = getchar();
printf("The char entered is: ");
putchar(myChar2);
printf("\n");
return 0;
}
When I run this program in my Terminal, the following is what I see, which is not how I expect it to behave.
cnewbie#cnewbies-MacBook-Pro c % ./a.out
Please enter a char: k
The char entered is: k
Please enter another char: The char entered is:
cnewbie#cnewbies-MacBook-Pro c %
When I run the program, it outputs "Please enter a char: " and waits for me to enter a char. I type k and hit return. Then it outputs not only "The car entered is: k" but also the other lines shown above all at once.
Question: Why doesn't my program wait for me to input another char?
I'm a beginner in C and I have no clue why this is behaving this way. Please help!!
getchar also reads white space characters including the new line character '\n' that is placed in the input buffer due to pressing the Enter key.
Instead use a call of scanf the following way
char myChar;
scanf( " %c", &myChar );
^^^^
Pay attention to the leading space in the format string. It allows to skip white space characters.

Using scanf() function two times: works in one case but not in other case [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 3 years ago.
I'm the learning the very basics of C programming right now, and I'm practicing the scanf() function. This very, very simple program takes in a number and a letter and uses the printf() function to display the number and letter.
If I ask the user to enter the number first, the program works, i.e., asks for a number, asks for a letter, and prints the input. If I ask for the letter first, the program asks for a letter but then doesn't ask for a number.
I've tried multiple ways and reordered it, but it doesn't seem to work.
This works:
#include<stdio.h>
void main(){
int number;
char letter;
printf("Enter letter...");
scanf("%c", &letter);
printf("Enter number....");
scanf("%d", &number);
printf("Number entered: %d and letter entered: %c.\n", number, letter);
}
But, this combination doesn't work:
#include<stdio.h>
void main(){
int number;
char letter;
printf("Enter number....");
scanf("%d", &number);
printf("Enter letter...");
scanf("%c", &letter);
printf("Number entered: %d and letter entered: %c.\n", number, letter);
}
The output I get for the first program is:
Enter letter...a
Enter number....9
Number entered: 9 and letter entered: a.
Which is correct
But the second case doesn't work, and I don't get why it wouldn't work -- skips the "enter letter" part
the output is
Enter number....9
Enter letter...Number entered: 9 and letter entered:
.
Context: I entered "a" for letter and "9" for number in the above example.
It turns out there's a surprising difference between %d and %c. Besides the fact that %d scans potentially multiple digits while %c scans exactly one character, the surprising difference is that %d skips any leading whitespace, while %c does not.
And then there's another easily-overlooked issue when you're using scanf to read user inputs, which is, what happens to all those newlines -- the \n characters -- that get inserted when the user hits the ENTER key to input something?
So here's what happened. Your first program had
printf("Enter letter...");
scanf("%c", &letter);
printf("Enter number....");
scanf("%d", &number);
The user typed a letter, and ENTER, and a number, and ENTER. The first scanf call read the letter and nothing else. The \n stayed in the input stream. And then the second scanf call, with %d, skipped the \n (because \n is whitespace) and read the number, just like you wanted.
But in your second program you had the inputs in the other order, like this:
printf("Enter number....");
scanf("%d", &number);
printf("Enter letter...");
scanf("%c", &letter);
Now, the user types a number and hits ENTER, and the first scanf call reads the number and leaves the \n on the input stream. But then in the second scanf call, %c does not skip whitespace, so the "letter" it reads is the \n character.
The solution in this case is to explicitly force the whitespace-skipping that %c doesn't do by default. Another little-known fact about scanf is that a space in a format string doesn't mean "match one space character exactly", it means "match an arbitrary number of whitespace characters". So if you change your second program to:
printf("Enter number....");
scanf("%d", &number);
printf("Enter letter...");
scanf(" %c", &letter);
Now, the space character in " %c" in the second scanf call will skip over the \n that was left over after the user typed the number, and the second scanf call should read the letter it's supposed to.
Finally, a bit of editorializing. If you think this is a bizarre situation, if you think the exception to the way %c works is kind of strange, if you think it shouldn't have been this hard to read a number followed by a letter, if you think my explanation of what's going on has been far longer and more complicated than it ought to have been -- you're right. scanf is one of the uglier functions in the C Standard Library. I don't know any C programmers who use it for anything -- I don't believe I've ever used it. Realistically, its only use is for beginning C programmers to get data into their first programs, until they learn other, better ways of performing that task, ways that don't involve scanf.
So my advice to you is not to spend too much time trying to get scanf to work, or learning about all of its other foibles. (It has lots.) As soon as you're comfortable, start learning about the other, better ways of doing input, and leave scanf comfortably behind forever.
Try this
#include <stdio.h>
int main(void) {
int number;
char letter;
printf("Enter letter...");
scanf("%s", &letter);
printf("Enter number....");
scanf("%d", &number);
printf("Number entered: %d and letter entered: %c.\n", number, letter);
return 0;
}
If you change the %c to %s then you get the correct output.
Add a space before %c. So, change this:
scanf("%c", &letter);
to this:
scanf(" %c", &letter);
As I have written in caution when using scanf, this will make scanf eat the whitespaces and special characters (otherwise it will consider them as inputs).
Here, it will consume the newline character, on other words, the Enter you press, after typing your input!
To be exact, in your example, think of what the user (in this case you) do:
You type 9
You press Enter
You type 'a'
You press Enter
Now, when you input something, from your keyboard in this case, this will go into the Standard Input buffer, where it will patiently await to be read.
Here, scanf("%d", &number); will come and read a number. It finds 9 in the first cell of the STDIN buffer, it reads it, thus deleting it from the buffer.
Now, scanf("%c", &letter); comes, and it reads a character. It finds the newline character, that's the first Enter you pressed, and the function is now happy - it was told to read a character, and that's exactly what it did. Now that newline character gets deleted from the buffer (now what's left in there is 'a' and a newline character - these two are not going to be read, since there is no other function call. left for that).
So what changes if I write scanf(" %c", &letter); instead?
The first scanf will still read the number 9, and the buffer will now have a newline character, the 'a' character, and another newline character.
Now scanf(" %c", &letter);` is called, and it goes to search for a character to read in the STDIN buffer, only that now it will first consume any special characters found.
So there it goes to the buffer, it firstly encounters the newline character, it consumes it.
Then, it will encounter 'a', which is not a special character, and therefore it will read normally, and stored to the passed variable in scanf.
The last newline character will remain in the STDIN buffer, untouched and unseen, until the program terminates and the buffer gets deallocated.
Tip: You probably meant to write int main(void), instead of void main(). Read more in What should main() return in C and C++?
Specifying scanf the following way
scanf("%c", &letter);
does not skip white spaces and can read for example a new line character stored in the input buffer when the user pressed Enter entering previous data.
Use instead
scanf(" %c", &letter);
^^^
to skip white spaces.
From the C Standard (7.21.6.2 The fscanf function)
8 Input white-space characters (as specified by the isspace function)
are skipped, unless the specification includes a [, c, or n specifier.
and
5 A directive composed of white-space character(s) is executed by
reading input up to the first non-white-space character (which remains
unread), or until no more characters can be read.
Pay attention to that according to the C Standard the function main without parameters shall be declared like
int main(void)
From the C Standard (5.1.2.2.1 Program startup)
1 The function called at program startup is named main. The
implementation declares no prototype for this function. It shall be
defined with a return type of int and with no parameters:
int main(void) { /* ... */ }

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

What's the output of following program which shows the unusual output and why?

see the ouput image
What's the output of following code and why?
I am curious to know why c compiler shows the unusual output.
What happens behind the scene?
#include<stdio.h>
int main()
{
char a,b,c;
printf("Enter First char:");
scanf("%c",&a);
printf("Enter Second char:");
scanf("%c",&b);
printf("Enter Third char:");
scanf("%c",&c);
return 1;
}
Enter First char:a
Enter Second char:Enter Third char:c
see above output, its not taking 2nd input and directly asking third one!
First time you type 1 and hit Enter (Enter is interpreted as newline character)
The first scanf reads '1'.
The second scanf reads '\n'.
Then you type 2 and click Enter. The third scanf reads '2'.
Probably you need to read "%c " or " %c", since ' ' in format string skips all whitespaces.

Beginner to C: Getting frustrated on a simple program

#include<stdio.h>
int main()
{
char a, b;
scanf("%c", &a);
scanf("%c", &b);
printf("%c %c",a,b);
return 0;
}
When I run this program, I only get output as a & I don't get the prompt to enter 2nd character. Why?
In this line,
scanf("%c", &a);
you are actually taking a %d from the stdin (standard input) but at the time you entered a character from stdin, you also typed ENTER from your keyboard which means that now you have two characters in stdin; the character itself & \n. So, the program took first character as the one you entered & second character as \n.
You need to use
scanf("%c\n", &a);
so that scanf eats the newline (that came by pressing ENTER) too.
As rodrigo suggested, you can use these too.
scanf(" %c", &a); or scanf("%c ", &a);
The way you are thinking that second character is printed is wrong. It's actually being printed but it's \n so your prompt might be coming to the next line.
Your code will work if you enter both characters without using ENTER.
shadyabhi#archlinux /tmp $ ./a.out
qw
q wshadyabhi#archlinux /tmp $
Note, when you used this, the only thing in STDIN was q & w. So, the first scanf ate q & the second one w.
Because when you press the enter key, the resulting newline is read as a separate character into b. Try this instead:
#include<stdio.h>
int main()
{
char a, b;
scanf("%c %c", &a, &b);
printf("%c %c",a,b);
return 0;
}
The %c is a format string which accepts only a single character. I think you pressed Enter key as soon as you pressed an alphabet key. The Enter key is also recognized as a character. So the next variable is taking the enter key which has a value of "\0".
The computer is still printing the character from the second variable but its invisible since nothing is getting printed. If you keenly observe, there will be a new line.
Enter two characters one after the other and you will be getting the right output.

Resources