Reputation: 88
i am trying to read input character until it is 'a'.however i need all the characters typed until a.the problem is it is also taking new line as a character.that is when i press a character(say f) an enter it is taking f as well as new line char in the next loop.
#include<stdio.h>
int main()
{
char val;
while(1)
{
printf("\nenter val: (a to stop)");
scanf("%c",&val);
printf("val is %d\n",(int)val);
if(val=='a')
break;
else
continue;
}
return 0;
}
output:
enter val: (a to stop)f
val is 102
enter val: (a to stop)val is 10
enter val: (a to stop)
Upvotes: 0
Views: 179
Reputation: 46
You can also use gets()
if you want to skip newline character as shown below
#include<stdio.h>
int main()
{
char val;
while(1)
{
printf("\nenter val: (a to stop)");
gets(&val);
printf("val is %d\n",(int)val);
if(val=='a')
break;
else
continue;
}
return 0;
}
Upvotes: 1
Reputation: 851
This is another way of implementing the same logic you want.You could add a space before the format specifier when you use scanf()
scanf(" %c",&val);
The leading space tells scanf()
to skip any whitespace characters (including newline) before reading the next character.
As many of them suggested you can use fgets
or fgetc
.
Upvotes: 1
Reputation:
Newline is a character, and the value of it is 10. If you don't want it, check if it is newline before printing.
include<stdio.h>
int main()
{
char val;
while(1)
{
printf("\nenter val: (a to stop)");
scanf("%c%*c",&val);
printf("val is %d\n",(int)val);
if(val=='a')
break;
else
continue;
}
return 0;
}
Upvotes: 1