'Need to know when a scentences end with own code, can't compare two array values. in C
So i just started coding with C and want to wake a program to know how many sentences there are in a text. However when making an array with a ".", "?" and "!" I get an error when comparing them to my text[i].
My code is as follows:
int main(void)
{
string text = "Hi there, i'm walking through the woods. Oh there is a branch, i need to jump over. I hope i don't fall.";
printf("%c \n", text[39]); // is a "."
printf("%c \n", text[82]); // is a "."
printf("%c \n", text[103]); // is a "."
printf("%c \n", text[-1]); // i would expect a "." here, but it doesn't show when executing the program. (total of 3 sentences)
char scanend[3] = {".", "?", "!"};
int sentences = 0;
for (int i = 0, n = strlen(text); i < n; i++)
{
if (text[i] == scanend[0] || text[i] == scanend[1] || text[i] == scanend[2])
{
sentences++;
}
}
printf("%i\n", sentences);
}
Why do I get an error when comparing these two array's? and how can i compare them without an error?
Thank you for your help!
Solution 1:[1]
I suppose that the name string is declared as a typedef name for char *. Otherwise you need to declare the variable text as having the type char * or const char *.
The initializer list in this declaration
char scanend[3] = {".", "?", "!"};
is incorrect. You are trying to initialize objects of the type char with pointers of the type char * to which string literals are implicitly converted.
Either write
char scanend[3] = {".?!"};
or
char scanend[3] = {'.', '?', '!'};
However it would be better to declare the array like
char scanend[] = {".?!"};
and instead of this if statement
if (text[i] == scanend[0] || text[i] == scanend[1] || text[i] == scanend[2])
{
sentences++;
}
to write
if ( strchr( scanend, text[i] ) != NULL )
{
sentences++;
}
Pay attention to that the expression text[-1] used in this call
printf("%c \n", text[-1]);
invokes undefined behavior.
Instead you could write
printf("%c \n", text[strlen( text ) - 1]);
Also the return type of the function strlen is size_t. So the for loop should look like
for ( size_t i = 0, n = strlen(text); i < n; i++)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
