Can some one explain me why I see a double input of the printf() function the while loop:
#include <ctype.h>
#include <stdio.h>
int main(){
int x = 0;
while ( x != 'q'){
printf("\nEnter a letter:");
x=getchar();
printf("%c\n", x);
if( isalpha(x) )
printf( "You entered a letter of the alphabet\n" );
if( isdigit(x) )
printf( "You entered the digit %c\n", x);
}
return 0;
}
The output of the code in Debian Squeeze (gcc version 4.4.5 (Debian 4.4.5-8)) is:
Enter a letter:1
1
You entered the digit 1
Enter a letter: // why is the first one appearing ???
Enter a letter:2
2
You entered the digit 2
The first one reads the line terminator character you entered when hitting Enter after 1 (the line terminator will remain in the input buffer).
You can verify this by adding an else branch:
#include <ctype.h>
#include <stdio.h>
int main()
{
int x = 0;
while ( x != 'q')
{
printf("\nEnter a letter:");
x = getchar();
printf("%c\n", x);
if( isalpha(x) )
printf( "You entered a letter of the alphabet\n" );
else if( isdigit(x) )
printf( "You entered the digit %c\n", x);
else
printf("Neither letter, nor digit: %02X\n", x);
}
return 0;
}
The output:
Enter a letter:1
1
You entered the digit 1
Enter a letter:
Neither letter, nor digit: 0A
Enter a letter:2
The byte 0A is the line-feed character.
The second time through the loop, getchar() is getting the Enter after the first char you entered.
You could do something like
while ((c = getchar()) != EOF && c != '\n') {} /* eat the rest of the line */
to get rid of everything up to and including the next Enter after getting a char and before asking for another.
If you want to check characters as you enter a slightly advanced technique would be to change stdin's behavior to raw mode.Then as soon as the user hits a char you get that in your variable.
Check this for some start
Use CTRL + D to get the functionality of the newline character without its side effect.
Related
I am creating a very basic calculator in C but the output is not coming as desired.
#include<stdio.h>
int main(int argc, char const *argv[])
{
/* code */
char ch;
int a,b,p=0;
scanf("%d",&a);
while(1)
{
ch=getchar();
if(ch==';')
{
p=2;
break;
}
scanf("%d",&b);
if(ch=='+')
{
a+=b;
}
if(ch=='-')
{
a-=b;
}
if(ch=='*')
{
a*=b;
}
if(ch=='/' && b!=0)
{
a/=b;
}
if(ch=='/' && b==0)
{
printf("INVALID INPUT\n");
p=2;
break;
}
}
if(p!=0)
printf("%d",a);
return 0;
}
The Output is always coming as the initial value which has been assigned to "a".
Output which is coming-
4
+
5
;
4
Expected output -
4
+
5
;
9
Can you please help me with this issue of why the expression is not getting evaluated correctly?
The line
scanf("%d",&a);
will consume the first number from the input stream, but it will leave the newline character on the input stream.
Therefore, when you later call
ch=getchar();
it will read that newline character. It will not read the + character.
If you want to read the + character, then you can change that line to the following:
scanf( " %c", &ch );
This line will first discard all whitespace characters and will match the first non-whitespace character on the input stream.
Afterwards, your program will have the desired output:
4
+
5
;
9
An alternative solution would be to discard the rest of the line after every call to scanf that uses the %d format specifier. That way, calling getchar immediately afterwards should read the + character as intended.
You can discard the remainder of an input line using the following code:
//discard remainder of input line
{
int c;
do
{
c = getchar();
} while ( c != EOF && c != '\n' );
}
Here is a more compact way of writing the same thing:
//discard remainder of input line
for ( int c; (c=getchar()) != EOF && c != '\n'; )
;
The only problem is in scanning the inputs.
As a tab or a new line must seperate the value supplied to scanf.
In short, just add \n at the end of scanf.
scanf("%d\n", &a);
scanf("%d\n", &b);
this should do it.
I was going to make a loop that if I type the alphabet then the ascii value comes out. Unless I type '0' in.
but result is as below. There is the code that I made below the result. Where the value 10 is coming from?
Press any Alphabet
A
65
Press any Alphabet
10
Press any Alphabet
char aski;
while(1)
{
printf("Press any Alphabet\n");
scanf("%c", &aski);
if (aski == '0')
break;
else
printf("%d\n", aski);
}
scanf reads an extra \n. ASCII of \n is 10. That's why you get 10. I suggest you to use getchar() to read extra \n.
#include <stdio.h>
int main()
{
char aski;
while (1)
{
printf("Press any Alphabet\n");
scanf("%c", &aski);
getchar();
if (aski == '0')
break;
else
printf("%d\n", aski);
}
return 0;
}
The output is:
Press any Alphabet
a
97
Press any Alphabet
b
98
PS: I stopped excution after, entering b.
When you are pressing enter you are in fact creating a \n (new line) This char has the value of 10, which is what is being printed.
char c = '\n';
printf("%d",c);
Would give you 10 as result.
Try this
char aski;
scanf("%c ", &aski);
Notice the space after the %c, this makes sure to read all whitespace inputted.
I am learning C and I am trying to use fgets() and strtol() to accept user input and just take the first character. I am going to make a menu that will allow a user to select options 1-3 and 4 to exit. I want each option to only be selected if '1', '2', '3', or '4' are selected. I don't want 'asdfasdf' to work. I also don't want '11212' to select the first option since it starts with a 1. I created this code so far while I started testing and for some reason this loops over the question and supplies a 0 to the input.
#include <stdio.h>
#include <stdlib.h>
int main() {
char a[2];
long b;
while(1) {
printf("Enter a number: ");
fgets(a, 2, stdin);
b = strtol(a, NULL, 10);
printf("b: %d\n", b);
}
return 0;
}
output
Enter a number: 3
b: 3
Enter a number: b: 0
Enter a number:
It should be:
Enter a number: 3
b: 3
Enter a number: 9
b: 9
You need to have enough room for the '\n' to be read or else it will be left in the input buffer and the next iteration it will be read immediately and thus make fgets() return with an empty string and hence strtol() returns 0.
Read fgets()'s documentation, it reads until a '\n' or untill the buffer is full. So the first time, it stops because it has no more room to store characters, and then the second time it still has to read '\n' and it stops immediately.
A possible solution is to increase the buffer size, so that the '\n' is read and stored in it.
Another solution, is to read all remaining characters after fgets().
The second solution could be cleanly implemented by reading one character at a time instead, since you are just interested in the first character you can discard anything else
#include <stdio.h>
#include <stdlib.h>
int main()
{
int chr;
while (1) {
// Read the next character in the input buffer
chr = fgetc(stdin);
// Check if the value is in range
if ((chr >= '0') && (chr <= '9')) {
int value;
// Compute the corresponding integer
value = chr - '0';
fprintf(stdout, "value: %d\n", value);
} else {
fprintf(stderr, "unexpected character: %c\n", chr);
}
// Remove remaining characters from the
// input buffer.
while (((chr = fgetc(stdin)) != '\n') && (chr != EOF))
;
}
return 0;
}
Hy everyone, so I wrote some code that should count characters that are typed in console by user, using getchar() and a while loop until EOF character is typed, but it adds more to the count variable that it should. For example, I enter 3 characters, and then EOF character(in this case 'z') and at the end It outputs that I entered 6 characters, if I enter 4 chars + 'z' it says 8, if 5 it says 10. It displays x2 number of charaters it should.
#include <stdio.h>
#define END 'z'
int main()
{
printf("Hello:\n");
int count = 0;
int c;
while ((c = getchar()) != END)
{
count++;
}
printf("You entered %d charaters.", count);
}
Why is that so? :/
Every time you enter a character with getchar() and after that press "enter", you enter one more char which is a newline character.
while ((c = getchar()) != EOF)
{
if (c=='\n')
continue;
count++;
}
This will solve your problem.
I have done some tests with your and my code, just to see if that was the problem. The output is here:
output with your code:
Hello:
a
s
d
df
You entered 9 charaters.
Hello:
asdf
You entered 5 charaters.
output with my code:
Hello:
a
s
d
f
You entered 4 charaters
the output should be something like this:
Enter Character : a
Echo : a
I wrote
int c;
while (c != EOF)
{
printf("\n Enter input: ");
c = getchar();
putchar(c);
}
But I get two Enter Input after the echos.
Two characters are retrieved during input. You need to throw away the carriage return.
int c = 0;
int cr;
while (c != EOF)
{
printf("\n Enter input: ");
c = getchar();
cr = getchar(); /* Read and discard the carriage return */
putchar(c);
}
Homework?
If so, I won't give a complete answer/ You've probably got buffered input - the user needs to enter return before anything is handed back to your program. You need to find out how to turn this off.
(this is dependent on the environment of your program - if you could give more details of platform and how you are running the program, we could give better answers)
take fgets eg:
char c[2];
if( fgets( c, 2, stdin ) )
putchar( *c );
else
puts("EOF");
and you dont have any problems with getchar/scanf(%c)/'\n' and so on.
Why don't you use scanf instead?
Example:
char str[50];
printf("\n Enter input: ");
scanf("%[^\n]+", str);
printf(" Echo : %s", str);
return 0;
Outputs
Enter input: xx
Echo : xx
scanf reference
#include <stdio.h>
#include <conio.h>
main(){
int number;
char delimiter;
printf("enter a line of positive integers\n");
scanf("%d%c", &number, &delimiter);
while(delimiter!='\n'){
printf("%d", number);
scanf("%d%c", &number, &delimiter);
}
printf("\n");
getch();
}