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.
Related
I wrote this program to read a small amount of Spanish and English words from a file and prompt for an English word and get the Spanish translation. To stop the program they must press enter only. The program doesn't stop however, it just keeps waiting for another word. This is the program
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE*in=fopen("input.txt","r");
char English[9][20],Spanish[9][20],word[20];
int find(char[],char[][20]);
for(int j=0; j<=8;j++)
fscanf(in,"%s",English[j]);
for(int r=0;r<=8;r++)
fscanf(in,"%s",Spanish[r]);
printf("type some English word to stop press enter only\n");
scanf("%s",word);
while(strcmp(word,"")!=0){
int t=find(word,English);
printf("the Spanish word for %s is %s\n",word,Spanish[t]);
printf("type some english word to stop press enter only\n");
scanf("%s",word);}
fclose(in);
}
int find(char word[],char English[][20]){
for(int j=0;j<=8;j++)
if(strcmp(English[j],word)==0) return j;
}
I thought pressing ENTER would save the empty string "" in the array word and the program would stop. This is the code for that.
while(strcmp(word,"")!=0)
I'm really new to coding, I don't know why it isn't working.
You can do it like this, just make the character q for quit:
while(strcmp(word,"q")!=0){
int t=find(word,English);
printf("the Spanish word for %s is %s\n",word,Spanish[t]);
printf("type some english word to stop press enter only\n");
scanf("%s",word);
}
printf("\nExiting...\n");
"New to coding" and "confused by scanf" is a universal truth. Seriously, do not use scanf at all until you understand the language well enough to realize that you do not really ever need it. That said, you can do:
$ cat a.c
#include <stdio.h>
int
main(void)
{
char word[1024];
char c;
int rc;
while( ( rc = scanf("%1023[^\n]%c", word, &c)) == 2 ) {
printf("word = %s\n", word);
}
return 0;
}
$ printf 'foo\nbar\n\nignored\n' | ./a.out
word = foo
word = bar
The format string matches everything up to a newline and stores it in word, and then consumes the newline with %c. (You could also use %*c and not provide a variable to be assigned.) When there are two adjacent newlines in the input stream, the first conversion specifier fails to match the second newline and the loop terminates. Note that this will fail if any line of input exceeds 1023 chars. Two general rules here: 1) %s cares about whitespace, and if you want to handle whitespace specially you should use %[ insteead of %s, and 2) always, always, always check the value returned by scanf. If you ever call scanf and it is not in an if condition or a loop control or the right hand side of an assignment, it is an error.
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.
Currently im trying to learn simple C Programs. But, i came into this situation :
#include<conio.h>
#include<stdio.h>
void main()
{
char c;
int tryagain=1;
while(tryagain>0){
printf("Enter the Character : ");
scanf("%c",&c);
printf("You entered the character \"%c\" and the ascii value is %d",c,c);
getch();
clrscr();
tryagain=0;
printf("You want to Trry again Press 1 : ");
scanf("%d",&tryagain);
clrscr();
}
}
The program is fine when user first enter a character. And, when it ask to continue. And, user enter 1 then it is behaving weired. It automatically input blank character and prints the ascii and goto the same place.
How can i resolve this? And, specially, Why is the reason for this?
And, Im sorry about my poor english!
Thank you in Advance.
When you use
scanf("%d",&tryagain);
the number is read into tryagain but the newline character, '\n', is still left on the input stream. The next time you use:
scanf("%c",&c);
the newline character is read into the c.
By using
scanf("%d%*c",&tryagain);
the newline is read from the input stream but it is not stored anywhere. It is simply discarded.
The issue is that you are reading a single number in the second scanf, but user inputs more than a single number there, the user also input a new line character by pressing .
User enters "1\n". Your scanf reads "1", leaving out "\n" in the input stream. Then the next scanf that reads a character reads "\n" from the stream.
Here is the corrected code. I use getc to discard the extra new line character that is there.
#include <stdio.h>
void main()
{
char c;
int tryagain = 1;
while (tryagain > 0) {
printf("Enter a character: ");
scanf("%c", &c);
printf("You entered the character \"%c\" and the ascii value is %d\n", c, c);
tryagain = 0;
printf("If you want to try again, enter 1: ");
scanf("%d", &tryagain);
// get rid of the extra new line character
getc(stdin);
}
}
Also, as a side note, you use conio.h which is not part of standard C, it's MS-DOS header file, thus it's not portable C you are writing. I have removed it from my code, but you might wish to keep it.
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.
#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.