我一直遇到关于for循环和数组的小问题,我希望能得到一些帮助。在第一个函数中,使用for循环调用函数的每个值都可以正常工作。但是,在第二个函数中,我从Visual Studio中得到一个错误,指出“下标需要数组或指针类型”。我在这里做错了什么导致了这个错误?
这个程序的目的是搜索书籍的txt文件,跳过条目之间的行,找出文件中有多少条目匹配以及它们在哪里,并打印出每个条目的详细信息。
void bookSearch(string id) {
ifstream fbooks;
string item = " ", entry = " ";
int resultLocation[30];
int searchType = 0;
fbooks.open("books.txt");
cout << "Welcome to the Book Search System, " << id << ".\n"
<< "What do you wish to search the registry by?\n"
<< "1. ISBN Number\n" << "2. Author\n" << "3. Title\n";
while (searchType<1 || searchType>3) {
cin >> searchType;
if (searchType<1 || searchType>3) {
displayMessage(0);
}
}
getline(cin, item);
for (int x = 0; x <= 30; x++) {
for (int y = 0; y < searchType; y++)
getline(fbooks, entry);
if (entry == item)
resultLocation[x] = 1;
else
resultLocation[x] = 0;
for (int z = 0; z < 5; z++)
getline(fbooks, entry);
}
resultPrint(resultLocation, id);
}
void resultPrint(int resultLocation, string id){
int resultNum = 0;
string entry = "";
ifstream fbooks;
fbooks.open("books.txt");
for (int a = 0; a <= 30; a++) {
if (resultLocation == 1)
resultNum++;
}
if (resultNum > 0) {
cout << endl << "There are " << resultNum << " entries in the database matching that criteria.\n";
for (int a = 0; a <= 30; a++){
if (resultLocation[a] == 1) { //The a in this line is marked with the error
for (int b = 0; b <= 2; b++) {
getline(fbooks, entry);
cout << entry;
}
}
}
}
else
cout << endl << "There are no entries in the database matching that criteria.\n";
}
答案 0 :(得分:0)
resultLocation
是一个整数,因此您不能在其上使用operator[]
(除了第一个“索引”之外)。看起来你打算把它变成一个数组:
void resultPrint(int resultLocation[], string id);