why the below code keep printing the value10? - c

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.

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++;.

My C program counts characters incorrectly

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

Simple program in C doesn't work

I'm new to C and I'm currently making a tutorial.
I have decided to combine two exercices and I want to take inputs
as long as I don't just do < return >. This is my code until now:
#include<stdio.h>
char letter;
int i=0;
int main() {
while (i==0) {
printf(">> ");
letter = getchar();
printf("%d\n", letter);
if (letter==10) { //10 is the ASCII id for <return>
printf("End\n");
i = 1;
}
printf("You've entered %c\n", letter);
}
}
The problems is that when I enter a letter for the first time, it does what I want it to do: take a number, and return it on the screen. Directly after that it sets 10 on it's on own!
This is the output:
>> r //I've entered 'r'
114
Das Zeichen ist r
>> 10 //I've entered nothing. It entered that on it's own
End
The letter is
What is going on here? Why does it do that? I didn't enter anything or pressed anything.
The reason that when you enter "r" you also press Enter ('\n' which equals to ASCII 10). The shortest way is to add another getchar() inserted to consume the '\n':
int main() {
while (i==0) {
printf(">> ");
letter = getchar();
getchar();
printf("%d\n", letter);
if (zeichen==10) { //10 is the ASCII id for <return>
printf("End\n");
i = 1;
}
printf("You've entered %c\n", letter);
}
}
There is also another short way which is comparing letter value early after it's assignment like following:
int main() {
while (i==0) {
printf(">> ");
letter = getchar();
if(letter == '\n')
continue;
printf("%d\n", letter);
if (zeichen==10) { //10 is the ASCII id for <return>
printf("End\n");
i = 1;
}
printf("You've entered %c\n", letter);
}
}
however you still need to assign zeichen to something otherwise you'll get undefined behavior
Standard portable C API are not good to handle keystrokes. To "enter r" you need to press "r" "return" so your program using getchar() will receive them both immediately. Your need to use ncurses or cornio.
while (i==0) {
printf(">> ");
letter = getchar();
printf("%d\n", letter);
if (zeichen==10) { //10 is the ASCII id for <return>
printf("End\n");
break;
}
Use break statement instead of i=1;
If using Windows, use _getch() from "conio.h"
Also, instead of checking for 10 (which is the linefeed character not Return), it is better to check for \r, which is what the ENTER key returns. Never use literal values when more descriptive escapes can be used:
line feed = \n
Return = \r
etc.

strange behavior of printf() inside a while loop

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.

Resources