My C program counts characters incorrectly - c

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

Related

Simple C code contains ((c = getchar()) != EOF)

I run the following simple C code.
int main()
{
int c;
while ((c = getchar()) != EOF)
{
putchar(c);
printf("%d\n", c);
}
return 0;
}
The output of code when I enter character A as input from keyboard is as follow:
>A
>A65
>
>10
>
Why does this code print the number 10 after each inner while loop?
Think about what you're doing when the program is asking for input.
Are you just hitting A?
No, you're hitting AEnter, and hitting the Enter key results in a newline, so your while loop is actually doing this:
1. Enter loop
2. getchar() waits for input from stdin
2. You enter 'A', hit 'Enter'
3. c is assigned '65' (integral value of 'A')
4. putchar(c) and then printf("%d\n"), so you see 'A65'
5. getchar() immediately gets next character from stdin, which is linefeed
6. c is assigned '10' (integral value of '\n')
7. putchar(c) and printf("%d\n"), so you see a newline followed by 10.
You can make your code ignore the linefeeds/non-printable characters if you want (this depends on your locale), using isprint:
#include <stdio.h>
#include <ctype.h>
int main() {
for(int c; (c = getchar()) != EOF;) {
if (!isprint(c)) {
printf("Ignoring character with value %d\n", c);
} else {
putchar(c);
printf("%d\n", c);
}
}
return 0;
}
And if I run this:
root#6f67da78fe9a:~# gcc -o chartest source.c
root#6f67da78fe9a:~# ./chartest
A
A65
Ignoring character with value 10

How do I get this getchar() function inside this while loop to return a value? (C)

So I'm unfamiliar with the getchar() function in C (because I'm new to programming).
I want to know how to make the code below take a number of characters (whether thru a file or by inputting from keyboard) and count them with a while loop which has the getchar() function. I want it to read up until the end of a file (or keyboard input).
As of right now the code doesn't return anything (even if you type in the commandline).
The OS I'm running this code from is Windows.
#include <stdio.h>
int main(void){
int blanks = 0, digits = 0, letters = 0, others = 0;
int c; //use for actual integer value of character
printf("WELCOME TO WHILE CHARACTER COUNTER: WRITE ANY CHARACTER:\n");
while ((c = getchar()) != EOF){
if (c == ' ') //counts any blanks on a text
++blanks;
else if (c >= '0' && c <= '9')
++digits;
else if (c >= 'a' && c <= 'z' || c >= 'A' && c<= 'Z')
++ letters;
else
++ others;
}
printf ("\nNumber of:blank characters = %d, digits = %d, letters = %d", blanks, digits, letters);
printf ("\nOther characters = %d", others);
return 0;
}
Your code works, in principle. For the input This is a test. followed by the newline character, followed by end-of-file, your program has the following output:
WELCOME TO WHILE CHARACTER COUNTER: WRITE ANY CHARACTER:
Number of:blank characters = 3, digits = 0, letters = 11
Other characters = 2
Click this link to test your program yourself with that input.
I suspect that your problem is rather one of the following:
You don't know how to execute your program in such a way that input is redirected from a file.
You don't know how to enter end-of-file on the keyboard.
In order to call your program in such a way that input is redirected from a file, on most operating systems, you can call your program the following way:
myprogramname < inputfile.txt
When you are reading input from a terminal/console, you can enter end-of-file the following way:
On Linux, you can use the keyboard combination CTRL+D.
On Microsoft Windows, you can use the keyboard combination CTRL+Z.

What are the numbers associated with printing getchar()?

Code:
int main(void) {
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
printf("%d", c);
}
}
I enter a character and that character is returned with putchar(c), however, if I print that character I get a code back? example:
0 = 48010
1 = 49110
2 = 50210
etc...
what are these numbers? is this where the character is stored in memory or something?
cheers
So I believe I figured out the problem by introducing newlines
int main(void) {
int c;
c = getchar();
while (c != EOF) {
putchar(c);
printf("\n");
c = getchar();
printf("%d\n", c);
}
}
When I enter 1 this returns the following in the terminal window.
49
1
10
What's happening is I'm returning the ASII character code for 1 - > 49
returning the value I entered with getchar()
and returning 10 which is the linefeed value i.e. the enter command.
Right? without the newlines it was just concatenating them all, making it confusing.

why the below code keep printing the value10?

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.

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