I have just started learning C, been reading a C textbook by Keringhan and Ritchie. There was this example in the textbook, counting characters from user input. Here's the code:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF) {
if (getchar() != 'q')
++nc;
else
break;
}
printf("%ld\n", nc);
}
The problem is, when I execute the code, if I input only one character per line, when I input "q" to break, it doesn't do so. I have to type some word per line, only after that it will break the loop. Also, it only counts the half of the characters of the word. I.e. if I input
a
b
russia
it will only print '5' as final result.
Could you please explain to me why is this happening?
This works, but only when you finish off with an Enter. So, this will count the characters until the first "q" appears. That is just how getchar() and getc(stdin) work.
#include <stdio.h>
int main() {
char c = 0;
long count = 0;
short int count_linebreak = 1; // or 0
while((c = getchar()) != EOF) {
if(c != 'q' && (count_linebreak || (!count_linebreak && c != '\n'))) {
++count;
}else if(c == 'q') {
printf("Quit\n");
break;
}
}
printf("Count: %ld\n",count);
return 0;
}
A StackOverflow question about reading stdin before enter
C read stdin buffer before it is submit
Related
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
I don't understand why the printf() call after the while loop does not get executed?
int main(){
while((getchar()) != EOF){
characters ++;
if (getchar() == '\n'){
lines++;
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}
I think you are trying to do that
#include<stdio.h>
int main()
{
int characters=0,lines=0;
char ch;
while((ch=getchar())!= EOF)
{
if (ch == '\n')
lines++;
else
{
characters++;
while((ch=getchar())!='\n'&&ch!=EOF); //is to remove \n after a character
}
}
printf("lines:%8d\n",lines);
printf("Chars:%8d",characters);
return 0;
}
Output:
a
s
d
f
^Z
lines: 1
Chars: 4
Process returned 0 (0x0) execution time : 8.654 s
Press any key to continue.
Note: ^Z(ctrl+z) is to send EOF to stdin (in windows)
You have to be careful of you're treatment in the while loop. Indeed, you are missing every caracter read in your while statement. You have to save this input, in order to use it afterwards.
The proper syntax would be while(( c = getchar()) != EOF)
You are probably looking for something like this:
#include <stdio.h>
int main()
{
int characters = 0;
int lines = 0;
int c;
while ((c = getchar()) != EOF) {
characters++;
if (c == '\n') {
lines++;
characters--; // ignore \n
}
}
printf("lines: %8d\n", lines);
printf("Chars: %8d", characters);
return 0;
}
while ((c = getchar()) != EOF) might look a bit confusing.
Basically it calls getchar, puts the returned valuee into c ands then checks if c equals EOF.
The folllowing C Program is to calculate the character Count .
#include <stdio.h >
int main()
{
int nc = 0;
while (getchar() != EOF)
{
++nc;
printf("%d\n", nc);
}
return 0;
}
When I Enter a character , for example 'y' in the terminal , The output returns as follows
1
2
How does this calculation happens and why 2 is in the output?
I suppose you didn't know but when you press enter you just insert a newline character or '\n'. If you want to get the correct result ignore the newline character or just decrease the nc by one.
#include <stdio.h>
int main()
{
int nc = 0;
while (getchar() != EOF)
{
++nc;
printf("Character count is:%d\n", nc - 1);
}
return 0;
}
Even better code:
#include <stdio.h>
int main()
{
int nc = 0;
for(;;)
{
do
++nc;
while (getchar() != '\n');
printf("Character count is:%d\n", nc - 1);
nc = 0;
}
}
The updated code will reset your counter back to 0.
You ENTERed "a character". A y and a new line character. That's 2.
Because you entered two character. One is y and another one is \n(newline) character.
Hence you get the output 1 and 2.
If you want to count only the visible bytes, you can use the isprint function, which returns whether a byte is printable or the space character. It goes like this:
#include <ctype.h>
#include <stdio.h>
int main()
{
int nc = 0;
int ch;
while((ch = getchar()) != EOF)
{
if (isprint(ch) && ch != ' ')
++nc;
printf("Character count after reading '%c' is %d.\n",ch, nc);
}
return 0;
}
Note that since in C, a char is not a Unicode character but often just a byte, this program counts some characters as 2 or more bytes, for example emojis, Cyrillic letters, Chinese ideographs.
When you hit enter it's considered a character
I have two problems writing my code. The first problem I have is getting my getchar() to work if the user enters no text and just hits enter. I need to print an error if they do so and prompt the user to reenter the text in a loop until they do enter text. Is there any way to do so because everything I have tried has failed.
Here is the code I have for that section:
printf("Enter a text message: ");
while((c=getchar()) != '\n' && c != EOF)
{
text[i]= c;
i++;
}
I am new to C so I am limited on ideas to fix my dilemma. As you can see I am setting the input equal to an array. This leads to my second problem, I need to limit the input to no more than 100 characters. But, instead of giving the user an error I need to just chop off the extra characters and just read the first 100.
The simplest solution to your problem is to use fgets. We can give limit to the input so that it doesn't read the extra characters after the given limit.
Refer this sample code. Here I am printing the string if the user is not pressing Enter key:
#include <stdio.h>
int main()
{
char str[100];
fgets(str, 100, stdin);
if(str[0] != '\n')
{
puts(str);
}
return 0;
}
#include <stdio.h>
#define MAXSIZE 100
int main() {
char text[MAXSIZE+1]; // one extra for terminating null character
int i = 0;
int c;
while (1) {
printf("Enter a text message: ");
i = 0;
while ((c = getchar()) != '\n' && c != '\r' && c != EOF) {
if (i < MAXSIZE) {
text[i]= c;
i++;
}
}
if (i > 0 || c == EOF)
break;
printf("Empty string not allowed.\n");
}
text[i] = '\0';
printf("You entered: %s\n", text);
return 0;
}
Test code to detect non-compliant system:
#include <stdio.h>
int main() {
int c;
printf("Just hit enter: ");
c = getchar();
if (c == '\r')
printf("\\r detected!!!\n");
else if (c == '\n')
printf("\\n detected.\n");
else
printf("Yikes!!!\n");
return 0;
}
First of all getchar() can take only one character an input. It cannot take more than one character.
char c;
int total_characters_entered = 0;
do
{
printf ("Enter a text message: ");
c = getchar();
if (c != '\n')
{
total_characters_entered++;
}
} while (total_characters_entered <= 100);
I have written some code that will iterate in while loop until user has entered 100 characters excluding "Simple Enter without any text"
Please let me know if it does not satisfy your requirement. We will work on that.
Im writing a simple program to count the number of character user is entered, and i wrote an if to check wether there is a newline but still printing it..
the code:
#include <stdio.h>
int main()
{
char ch;
int numberOfCharacters = 0;
printf("please enter a word, and ctrl + d to see the resault\n");
while ((ch = getchar()) != EOF)
{
if (numberOfCharacters != '\n')
{
numberOfCharacters++;
}
}
printf("The number of characters is %d", numberOfCharacters);
return 0;
}
what am i doing wrong?
Think about this line:
if (numberOfCharacters != '\n')
how can it make sense? You are comparing the number of characters read so far with a newline, it's like comparing apples to oranges and surely won't work. It's another variable that you should check...
Change your loop to this.
while ((ch = getchar()) != EOF)
{
if(ch != '\n')
numberOfCharacters++;
}