I'm new to C/C and I'm doing this exercise in my course that requires a while
loop, and this code supposedly counts characters without spaces. I'm really confused why this counts the spaces as well, because I used a similar syntax with fgets
instead of getchar
and it worked fine.
int main()
{
//method 2
char str[100];
int i = 0;
char c;
int count2 = 0;
printf("Enter characters.\n");
while (c = getchar() != '\n') {
if (c != ' ') {
count2 ;
}
}
printf("There are %d characters\n", count2);
return 0;
}
CodePudding user response:
#include <stdio.h>
int main(){
int i = 0;
char c;
int count2=0;
printf("Enter characters.\n");
c=getchar();
while (c!='\n')
{
if (c != ' ')
{
count2 ;
}
c=getchar();
}
printf("There are %d characters\n", count2);
return 0;
}
This is the right version. It seems that the check in the cycle try to do getchar()!='\n'
and after the assignment of the value to the variable c
CodePudding user response:
There are multiple problems in your code:
you must include
<stdio.h>
to callgetchar
andprintf
the test
while (c = getchar() != '\n')
is parsed asc = (getchar() != '\n')
:c
gets the value1
for all bytes except the newline, hence all bytes in the line are counted.You should instead write:
while ((c = getchar()) != '\n') ...
the
while
loop never stops if the file does not contain a newline. You should also test forEOF
:while ((c = getchar()) != EOF && c != '\n') ...
to properly test for
EOF
, you must definec
with typeint
.
Here is a modified version:
#include <stdio.h>
int main() {
//method 2
int c, count2;
printf("Enter characters.\n");
count2 = 0;
while ((c = getchar()) != EOF && c != '\n') {
if (c != ' ') {
count2 ;
}
}
printf("There are %d characters\n", count2);
return 0;
}