STRCMP功能不能正常工作 [英] strcmp function not working properly
问题描述
我有一个 删除
功能结构上的图书
的数组。我传递给它的记录数组,一书的作者
和书的名字
和列表的大小
。
I have a delete
function on array of structures books
. I'm passing it an array of records, author of book
and name of book
and size of the list
.
现在这里的因为列表[0] .author
和列表[5] .author
和作者
都是等于丹·布朗(相同的字符串)
Now here given that list[0].author
and list[5].author
and author
all are equal to "Dan Brown" (same string)
void delete(struct books *list,char author[],char name[],int n)
{
int i,a;
a=strcmp(list[0].author,list[5].author);
printf("%d\n",a); // prints 0
a=strcmp(list[0].author,author);
printf("%d\n",a); // prints other than 0
}
为什么会发生?什么是错在这里?
Why is it happening? What's wrong here?
推荐答案
从 <文档code>与fgets :
阅读停止。 新行,如果有的话,将被保留。
这意味着与fgets
将不可以删除最后一个的'\\ n'
从读出字符串的结尾。因此,你的字符串是:
This means that fgets
will not remove the final '\n'
from the end of the read string. Thus, your strings are:
- 丹·布朗的
- 丹·布朗的
- 丹·布朗\\ n
他们的不可以相等的。
这使用与fgets
的时候是一个非常普遍的问题。这就是为什么我通常preFER scanf函数
,就像这样:
This is a very common issue when using fgets
. That's why I usually prefer scanf
, like this:
char buffer[BUF_LEN];
char format[16];
int scanf_result;
sprintf(format, "%%%u[^\n]", BUF_LEN);
//....
do
{
//TODO: Ask for input
scanf_result = scanf(format, buffer);
switch (scanf_result)
{
case -1: //TODO: Print error message and exit
case 0: //TODO: Print error mesage and break
}
//Discard remainings of buffered input line
while (getchar() != '\n') {;}
} while (1); //Ugly, but plain
否则,您可以使用与fgets
的东西是这样的:
int buf_len;
//TODO: Ask for input
while (fgets(buffer, BUF_LEN, stdin) == NULL)
{
//TODO: Check and handle error
}
buf_len = strlen(buffer);
//Remove trailing '\n', if present
if (buffer[buf_len - 1] == '\n')
{
buffer[--buf_len] = '\0';
}
尽管这是比较容易的,我不喜欢这种第二种方法,因为的strlen
扫描串另一个时间来确定它的长度。在大多数情况下,这不是一个性能问题,我不去,因为我有我自己的心理问题。
Even though it's easier, I don't like this second method, because strlen
scans the string another time to determine its length. In most cases, this is not a performance issue, I avoid it because I have my own mental issues.
这篇关于STRCMP功能不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!