需要知道气味何时以自己的代码结束,无法比较两个数组值。在C中
所以我刚开始用 C 编码,想唤醒一个程序来知道文本中有多少个句子。然而,当用“.”、“?”创建数组时和 ”!”将它们与我的文本[i]进行比较时出现错误。
我的代码如下:
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);
}
为什么在比较这两个数组时出现错误?我怎样才能比较它们而不出现错误?
感谢您的帮助!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为名称
string
被声明为char *
的 typedef 名称。否则,您需要将变量text
声明为char *
或const char *
类型。此声明中的初始值设定项列表
不正确。您正在尝试使用字符串文字隐式转换为的 char * 类型的指针来初始化 char 类型的对象。
要么写
要么
但是最好像
and 那样声明数组,而不是这样的 if 语句
来写
请注意,此调用中使用的表达式 text[-1]
会调用未定义的行为。
相反,您可以编写
函数
strlen
的返回类型是size_t
。所以 for 循环应该看起来像I suppose that the name
string
is declared as a typedef name forchar *
. Otherwise you need to declare the variabletext
as having the typechar *
orconst char *
.The initializer list in this declaration
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
or
However it would be better to declare the array like
and instead of this if statement
to write
Pay attention to that the expression text[-1] used in this call
invokes undefined behavior.
Instead you could write
Also the return type of the function
strlen
issize_t
. So the for loop should look like