比较字符串不起作用

时间:2018-05-21 17:20:53

标签: c if-statement

我无法理解为什么在7-6行(结尾)当我输入相同的书名时它没有进入“if”。我在它上面写了printf线来检查打印是否有任何不同,但它不是。它为a.name和bookz [r] .name打印相同的东西。

谢谢!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


#define BOOK_NUM        50
#define NAME_LENGTH     200
#define AUTHOR_NAME_LENGTH  100
#define PUBLISHER_NAME_LENGTH   50
#define GENRE_LENGTH        50

typedef struct book {
    char name[NAME_LENGTH];
    char author[AUTHOR_NAME_LENGTH];
    char publisher[PUBLISHER_NAME_LENGTH];
    char genre[GENRE_LENGTH];
    int year;
    int num_pages;
    int copies;
} Book;

int main()
{
    int opt = 1;
    int i = 0, r = 0, k = 0, years, pagess, copiess, copies_to_add;
    Book bookz[50];
    int zeros[5] = { 0, 0, 0 ,0 ,0 };
    Book a;
    char c;
        // Add book to library
        printf("Please enter book name: ");
        scanf("\n%[^\n]s", &a.name);
        for (i = 0; i < BOOK_NUM; i++)
        {
            if (zeros[i] == 0)
            {
                scanf("\n%[^\n]s", &a.author);
                scanf("\n%[^\n]s", &a.publisher);
                printf("Please enter book genre: ");
                scanf("\n%[^\n]s", &a.genre);
                scanf("%d", &a.year);
                scanf("%d", &a.num_pages);
                scanf("%d", &a.copies);
                k = i;
                bookz[k] = a;
                zeros[i] = 1;
                printf("The book %s was successfully added!", a.name);
                break;
            }
            else
            {
                for (r = 0; r < i+1; r++)
                {
                    printf("%s %s", bookz[r].name, a.name);
                    if (bookz[r].name == a.name)
                    {
                        printf("The book already exists. Please enter the number of copies to add:");
                        scanf("%d, &copies_to_add");
                        bookz[i].copies = bookz[i].copies + copies_to_add;
                        printf("Additional copies (%d) of book %s were successfully added!", copies_to_add, a.name);
                        break;
                    }
                }

            }
        }

1 个答案:

答案 0 :(得分:1)

使用strcmp().

可以最好地实现C中的字符串比较