Using getchar(); to define multiple variables [duplicate] - c

This question already has answers here:
Clarification needed regarding getchar() and newline
(4 answers)
Closed 4 years ago.
I have this following code.
#include <stdio.h>
int main () {
char letter1;
char letter2;
printf("Enter Letter 1: ");
letter1 = getchar();
printf("\n");
printf("Enter Letter 2: ");
letter2 = getchar();
printf("\n");
printf("%c - %c\n", letter1, letter2);
return(0);
}
I am trying to use getchar() to define letter1 and letter2, however it will only work for letter1, then set the value of letter2 to '\n'. Does anyone know a work around for this, so I can type values for both variables?

This is because when you press the first letter and type the Enter key, you send the codes for the letter and the '\n' one after the other to the input buffer from where it will be consumed.
So the first getchar() get the code for the letter you typed and thus the letter is removed from the input buffer but that of \n remains which is consumed by the next getchar().
Inorder to avoid this, you need to keep consuming from the input buffer till the '\n' is consumed.
One way of doing this is
int c;
while( (c=getchar())=='\n' && c!=EOF);
This will keep on consuming from the input buffer as long as the read character is a \n and EOF is not reached. getchar() would return EOF on error.
int letter1, letter2;
int c;
printf("Enter Letter 1: ");
letter1 = getchar();
printf("\n");
printf("Enter Letter 2: ");
while( (c=getchar())=='\n' && c!=EOF);
letter2=c;
printf("\n");
printf("%c - %c\n", letter1, letter2);
Edit: As pointed out in the comments, note that getchar() returns an int and not a char. See this post.

Related

loop 2 taking input automatically

My code is behaving weirdly. In loop 1 it is working perfectly but in loop 2 it is automatically printing ASCII value 10. please help!.
#include<stdio.h>
int main(){
char c;
int loop =1;
do{
printf("\nLoop = %d\nWrite character of which you want to find acii values: ", loop);
scanf("%c", &c);
printf("\nASCII value of %c is %d.", c, c);
loop++;
}while(c != 'Z');
printf("\n******END*****");
return 0;
}
10 is ASCII for newline. You are reading whitespace, which you can avoid by using
scanf(" %c", &c);
Note the additional blank before the character specifier. It instructs scanf to ignore white space.

C: Nested do while loop not looping correctly

This code is supposed to -
Count the number of characters from input sequence.
Repeat the action until user exits the program.
Use nested do-while loop to achieve this purpose.
But the inner loop is executed only once.
Why?
#include <stdio.h>
int main ()
{
int x;
char i, ans;
i = '\0';
do
{
i = '\0';
x=0;
printf("\nEnter sequence of character:");
do
{
i = getchar();
x++;
}
while(i!='\n');
printf("\nNumber of characters entered is: %d", --x);
printf("\nMore sequences (Y/N) ?");
ans = getchar();
}
while(ans =='Y' || ans == 'y');
After you read the answer yes/no (the line with ans = getchar();), you'll read an "y" and a "\n". You'll consume the "y" and process it, but the next iteration when you read i = getchar();, i will consume the remaining "\n", so will break that do-while loop.
Although it's not my favourite solution, a simple workaround is this:
#include <stdio.h>
int main ()
{
int x;
char i, ans;
i = '\0';
do
{
i = '\0';
x=0;
printf("\nEnter sequence of character:");
do
{
i = getchar();
x++;
}
while(i!='\n');
printf("\nNumber of characters entered is: %d", --x);
printf("\nMore sequences (Y/N) ?");
ans = getchar();
getchar();
}
while(ans =='Y' || ans == 'y');
}
So just consume that extra "\n". This will work only if you type "y" followed by "\n" in terminal. If you type any extra characters, you'll have undefined behaviour.
Note: In your version, try to type: "y1234" then enter when prompted if you want to input again. You'll see that in fact the nested do-while loop works and will count the 4 characters after "y".
What happened:
getchar is a macro that gets a character from stdin.
The delimiter ('\n' in this case) is counted as a separate
character that remains in the buffer and is retrieved the next time
getchar() is called.
This causes inner loop to exit.
What could be done:
Insert the following after ans = getchar();
i = getchar();
if(i != '\n')
ungetc(i,stdin);
New code explained:
ungetc(int x,FILE *stream) pushes a character back into input stream.
stdin is the standard input stream defined in <stdio.h>.
We are reading a character and putting it back if it is not '\n'.
Not exactly sure, but I think that when the user presses enter to finish the 1st input character the input buffer keeps then enter button as the \n character. Try adding if(i == '\n') getChar(); after the x++;.

C program neglect in getting character after a string [duplicate]

This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 6 years ago.
My problem is that the scanf for the character is skipped and it doesn't check scan the char to see if I want to repeat the program again or not so why this is happening?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number,check;
char rep;
printf("Program to check if number is even or odd");
while( (rep!='N') || (rep!='n') )
{
printf("\n\nPlease enter the number: ");
scanf("%d",&number);
check = number%2;
if(check != 0)
printf("\nNumber is odd.");
else
printf("\nNumber is even.");
printf("\n");
printf("Do you want to enter number again?\nY=yes\tN=no\n");
scanf("%c", &rep);
}
return 0;
}
Change scanf("%c", &rep); to scanf(" %c", &rep);.
This is because a '\n' is left in stdin the first time you input a number. When executing scanf("%c", &rep);, that '\n' is immediately consumed by scanf() and assigned to rep. Since '\n' is equal to neither 'N' nor 'n', that loop continues.
With the leading space in the format string, all whitespace characters are discarded before reading starts. In your case, the invisible '\n' will be ignored, so that you can input a character.
Also, you should write char rep = 0; instead, in case the original value of rep happens to be 'n' or 'N'.

Scanf Skip scanning character [duplicate]

This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 6 years ago.
My problem is that the scanf for the character is skipped and it doesn't check scan the char to see if I want to repeat the program again or not so why this is happening?
#include <stdio.h>
#include <stdlib.h>
int main()
{
int number,check;
char rep;
printf("Program to check if number is even or odd");
while( (rep!='N') || (rep!='n') )
{
printf("\n\nPlease enter the number: ");
scanf("%d",&number);
check = number%2;
if(check != 0)
printf("\nNumber is odd.");
else
printf("\nNumber is even.");
printf("\n");
printf("Do you want to enter number again?\nY=yes\tN=no\n");
scanf("%c", &rep);
}
return 0;
}
Change scanf("%c", &rep); to scanf(" %c", &rep);.
This is because a '\n' is left in stdin the first time you input a number. When executing scanf("%c", &rep);, that '\n' is immediately consumed by scanf() and assigned to rep. Since '\n' is equal to neither 'N' nor 'n', that loop continues.
With the leading space in the format string, all whitespace characters are discarded before reading starts. In your case, the invisible '\n' will be ignored, so that you can input a character.
Also, you should write char rep = 0; instead, in case the original value of rep happens to be 'n' or 'N'.

i cant get this program to work correctly.

I have been asked to modify a program to read characters rather than numbers.
i modified the array into a char array. changed the two "%d" to "%c" as below
void main (void)
{
char a[100];
int counter;
int b;
counter = 0;
printf("please enter the length of the array: ");
scanf("%d", &b );
while (counter != b)
{
printf("please enter character: ");
scanf("%c", &a[counter]);
counter++;
}
a[counter] = '\0' ;
counter = 0;
while (a[counter] != '\0')
{
printf("\n");
printf("%c",a[counter]);
counter++;
}
}
when i run this the program does this:
please enter the length of the array: (4)
please enter character: please enter character: (a)
please enter character: please enter character: (a)
a
a
() are used to indicate the user inputs.
would be really good if i could get some help.
You have to remember that scanf leaves the newline in the input buffer, so when you try to read a character it will that newline.
The solution is very simple: Tell scanf to read and discard leading whitespace, by adding a space in the format code:
scanf(" %c", &a[counter]);
/* ^ */
/* | */
/* Note space here */

Resources