-
read line of character
I want to type a line of character , and from there calculate the vowel , consonant and space .
I tried to run the program , but after typing few random character , the setup stopped working
what's the problem ??
someone please points out my mistakes
thank you !
Code:
#include<stdio.h>
int main()
{
char line[150];
int i, v, c, s;
v = c = s = 0;
printf("Enter a line of character :");
gets(line);
for ( i= 0; line != '\0' ; ++i)
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' || line[i] == 'o' || line[i] == 'u' )
++i;
else if (line[i] >='a' && line[i] <= 'z' )
++c;
else if (line[i] ==' ' )
++s;
printf("vowel = %d \n consonant = %d \n space =%d ", v , c, s );
return 0;
}
-
Line #17. Change
line will never equal '\0', since it's just the name of the array, and has a constant address. Did you forget something?
-
hmm...I don't really understand ...
would you mind to explain more ?
actually I don't really understand why '' line !='\0' "
-
The problem is probably with your for loop
Code:
for ( i= 0; line != '\0' ; ++i)
if (line[i] == 'a' || line[i] == 'e' || line[i] == 'i' || line[i] == 'o' || line[i] == 'u' )
++i;
else if (line[i] >='a' && line[i] <= 'z' )
++c;
else if (line[i] ==' ' )
++s;
If you turn on compiler warnings, you will notice the following problems:
line is char * and you are trying to compare it with a char - as Adak mentioned, probably not what you want
Your variable v is initialized to 0 at the beginning and then never touched again before you print it out.
EDIT: Not exactly a mistake, but your program gives output and then does not end it with a newline. Although its not strictly required, the normal convention is to end each line with a newline. Not doing so would be like leaving the door open as you leave someone's house.
-
ok..
so what should I change in the loop in order for the program to run correctly ?
-
I think Adak was trying to hint at the answer without giving it explicitly. How are you comparing to see if the current character is a vowel?? The same method can be used to see if the current character is a '\0'. The symbol '\0' is just a special character that marks the end of the string.
Also notice that you are incrementing i inside your for statement as well as inside the loop body. Don't do this unless you know why you are doing it. For example, suppose the input is
bbba
What will happen when i==3 ?
Also one more thing to notice: the program is only guaranteed to work if your user enters 149 characters or less. Entering 150 characters or more results in undefined operation. Hint: don't use gets.
-
ok.
I have figure out the problem
add [i] to line
and the program work
thank you !