+ 3
doubt in c : character counting
#include<stdio.h> int main() { long x=0 ,a=getchar(); while(a!=EOF) { printf("%ld",x); x++; getchar(); } } input : abvd output : 01234 then the program asks for input again my question: 1. why is 01234 printed first and why doesn't the program asks for input after 0 2. how come every character is counted instead of counting the word Thank you for your time
14 Respuestas
+ 7
Not exactly, this below should not work perfectly but better :
doubt in c : character counting
#include <stdio.h>
#include <ctype.h> // for isalpha
int main()
{
long x=0;
char a=getchar();
int in_word = 0;
while(a!=EOF){
if(in_word && !isalpha(a)){
printf("%ld",x);
x++;
in_word = 0;
}else if(isalpha(a))
in_word = 1;
a = getchar();
}
x += in_word; //edited thanks to @Gordie
return 0;
}
With the in_word, you can prevent counting 3 word instead of two in syntaxes like that :
"Hello, World"
It does not work perfectly because it does not accept word with characters in it (like "tom's car" should be 2 words but 3 will be counted)
+ 6
EOF go charecter by character and on Sololearn you can enter input only on begging...
+ 5
getchar read a character. It ask for input only if the input buffer is empty (before you enter 0 and after it read 4)
As it reads character by character, you will count characters and not words. For it to count words, you'll have to modify the while loop
What's more, your program will never stop by itself, is it what you wanted to do ?
PS : I think you forgot to copy "a =" in the last line of the while loop
+ 4
@Gordie, I said it is flawed ^^
To fix this bug, I should add :
x += in_word;
Just after the while loop
+ 3
@~ swim ~ I am sorry, I do not understand what you meant ... I tried to see if there was a bug in my code but I did not see one. What is it that it lacks ? :/
+ 3
@~ swim ~ I know this output is odd, of course ! I just wanted to stay as near as I could to the original author's work
Correction would be :
printf(..., ++x);
With no x++ line
+ 2
guys i got a code, from the book im learning from, that i can't understand and according to the book, its the proper code for counting word, tab, space . It would be really helpful if you could explain me the working of while loop and if statement in this code
https://code.sololearn.com/ccC16fOeYPQ3/?ref=app
0
one more question
. i tried it on a normal compiler but still input is asked after 4
and not after 0. can you pls explain why
0
thanks man
for counting words i should add this, right?
if (a=='\t')
{ printf ("a = %f",a); }