0

我已经在这里潜伏了很长时间,感谢您过去的所有帮助,即使这是我不得不问的第一个问题。

我正在尝试制作一个简单的数据库程序,但我遇到了它的搜索要求。搜索时,如果用户不知道值,则需要能够输入问号。如果您知道一部电影是 90 年代的,您可以输入 199 吗?它会找到所有匹配 199_ 的电影。编译时我不断收到错误,“无法将 'char*' 转换为 'char ( )[5] for argument '2' to 'bool compareYears(const char , char (*)[5]”它是我自己的,我喜欢在将它们添加到主文件之前分离这些函数并让它们在一个单独的 .cpp 文件中工作,只是为了使调试更容易。

#include <iostream>
#include <cstring>
#include <fstream>
#include <cctype>
using namespace std;

const int yearLength = 4;
typedef char year[yearLength + 1];

bool compareYears(const year year1, year year2[]);

int main()
{
    year year1 = "1992"; //year from database, will be assigned the 
                         //  variable when implemented in main program. 
    year year2;          //year entered by user, it will be compared to year1.

    cout << "Enter a year to search for: ";
    cin >> year2;
    cout << endl;

    if((compareYears(year1, year2)) == true)
        cout << "they match\n";
    if((compareYears(year1, year2)) == true)
        cout << "they do not match\n";

    return 0;
}

bool compareYears(const year year1, year year2[])
{
    for(int i = 0; i < 4; i++)
    {
        if (strncom(year1, year2[i], 4) ==0)
            return true;
        else if (strncmp(year1, "????", 4) == 0)
            return true;
        else
            return false;
    }
}

谢谢你帮我解决这个问题,通常我从别人那里得到的最多的帮助是无用的或侮辱性的。我最需要帮助的是摆脱那个编译器错误。我这辈子都想不通。

4

3 回答 3

1

首先阅读这个:typedef 固定长度数组

然后,使用这个 typedef:

typedef struct year { char characters[4]; } year;

并以这种方式更改代码:

int main()
{
    year year1; 
    year1.characters= "1992"; //year from database, will be assigned the variable when implemented in main program. 
    year year2;          //year entered by user, it will be compared to year1.

    cout << "Enter a year to search for: ";
    cin >> year2.characters;
    cout << endl;

    if((compareYears(year1, year2)) == true)
        cout << "they match\n";
    else
        cout << "they do not match\n";

    return 0;
}

bool compareYears(year year1, year year2)
{
    if (strncom(year1.characters, year2.characters, 4) ==0)
        return true;
    else if (strncmp(year1, "????", 4) == 0)
        return true;
    return false;
}

我还修复了一些逻辑错误

于 2013-12-04T08:12:52.053 回答
1

只需更改这些行,它就会起作用...函数声明需要一个年份数组,而您正在尝试传递一个变量..

if((compareYears(year1, &year2)) == true) //this changed from year2 to &year2
cout << "they match\n";
if((compareYears(year1, &year2)) == true) //this changed from year2 to &year2
cout << "they do not match\n";
于 2013-12-04T08:25:32.497 回答
0

year2for 参数的类型compareYears看起来很奇怪。看起来这个参数是mask要测试的,即像文字年份1992或使用通配符的东西。因此,如何将其设为 charyearLength字节数组?

只写一个给定两个字符串或任意长度(第二个可能使用通配符)并查看它们是否相等的通用函数可能会更容易。质量测试可以首先查看两个字符串的长度是否相同,如果是,则两个字符串中每个位置的字符是否相等,或者第二个字符串中给定位置的字符是否为“?”。您可以使用单个循环并行遍历两个字符串来执行此操作。

于 2013-12-04T08:06:36.400 回答