Reputation: 11
My code was to count no of words in the string. But (a[i]=='') is showing empty character constant error
#include <stdio.h>
int main() {
char a[20];
int i,c1=0,c2=0;
scanf("%[^\n]",a);
for(i=0;a[i]!='\0';i++)
{
c1++;
if(a[i]=='')
c2++;
}
printf("%d\n",c1);
printf("%d",c2+1);
return 0;
}
For input - tom is here
I expect the output to be -11 3
Compilation error- In function 'main':
prog.c:10:15: error: empty character constant if(a[i]=='') ^
Upvotes: 1
Views: 162
Reputation: 25546
In contrast to empty string literal (""
), character literals always need to contain a character (exactly one)*. Replace ''
with ' '
and you code should compile at least.
However, the code as is will count the number of spaces. What will happen if a string contains more than one subsequent space? Additionally, you might want to consider tabs as well? And how would you want to interpret punctuation marks? Part of words or separator? And what about numbers?
Depending on how you answer all these questions, you might need to vary the condition in code below. In any case, I propose a stateful iteration over your input:
int isSeparator = 1; // so you will count the first word occuring, too, even if starting
// at first character of the string
for(char const* s = str; *s; ++s)
{
if(isalnum((unsigned char)*s)) // requires <ctype.h> header; modify condition
// appropriately if you want different
// characters to count as word parts
{
wordCount += isSeparator;
isSeparator = 0;
}
else
{
isSeparator = 1;
}
}
*Actually, the standard does allow multi-byte characters, so to be precise, we'd need to state 'at least one character', but these multi-byte characters have implementation defined meaning and usually aren't useful anyway, so for practical reasons, we might stay with the technically less correct 'exactly one character'...
Upvotes: 1
Reputation: 37
#include <stdio.h>
int main() {
char str[50];
int i, numberOfWords=0;
gets(str);
for(i=0; str[i]!='\0'; i++) {
if(str[i] == 32) //ascii code of space is 32
numberOfWords++;
}
printf("number of words = %d\n", numberOfWords + 1);
//adding 1 to numberOfWords because if there are two words, there will be 2-1=1 space between them. eg= "Hello World"
return 0;
}
Upvotes: 1