Мешает апостроф

269
10 февраля 2019, 07:50
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void sort(string titls[], int n);
bool isconsist(string titls[], const string &f, int first, int last);
int main()
{
    ifstream ifile("SetList.txt");
    if (!ifile)
    {
        cout << "Cannot open file";
        return 1;
    }
    string titls[25];
    string tit;
    int i{0};
    cout << "Reading SetList.txt file into array\n";
    while (getline(ifile, tit))
    {
        titls[i] = tit;
        i++;
    }
    ifile.close();
    cout << "Sorting array\n";
    sort(titls, i);
    cout << "Sorting done\n";
    string find;
    cout << "Please enter a song or END to terminate: ";
    getline(cin, find);
    while (find != "END")
    {
        if (isconsist(titls, find, 0, i))
            cout << find << " is on the set list\n";
        else
            cout << find << "  is NOT on the set list\n";
        cout << "Please enter a song or END to terminate: ";
        getline(cin, find);
    }
    cout << " Program ends";
    return 0;
}
void sort(string titls[], int n)
{
    for (int i = 0; i != n; i++)
    {
        for (int j = 0; j != n - i - 1;j++)
        {
            if (titls[j] > titls[j+1])
                swap<string>(titls[j], titls[j + 1]);
        }
    }
}
bool isconsist(string titls[], const string &f,int first, int last)
{
    int middle = (first + last) / 2;
    if (titls[middle] == f)
        return true;
    else if (first == middle)
        return false;
    else if (titls[middle] > f)
        last = middle - 1;
    else
        first = middle + 1;
    return isconsist(titls, f, first, last);
}

Файл:

Green Onions
Hold On, I’m Coming
Night Train
Respect
Ninety-Nine and a Half
The Thrill Is Gone
Soul Man

Не находит название: Hold On, I’m Coming, но в режиме отладки находит... Я понял, что это из-за апострофа. Можно это как-то пофиксить?

Answer 1

Какова семантика вашего параметра last в isconsist?

При первом вызове вы в качестве last передаете общее количество элементов, т.е. индекс за последним элементом диапазона поиска. Однако при последующих рекурсивных вызовах вы в качестве last можете вдруг передавать именно индекс последнего элемента диапазона поиска. Так все таки что такое last: это "индекс за последним" или "индекс последнего"?

Эта каша в трактовке параметра last приводит к неработоспособности функции. Например

string titls[] = { "A", "B", "C", "D" };
bool is = isconsist(titls, "B", 0, 4);

возвращает false именно из-за этой ошибки. И никаких "мешающих апострофов" не надо.

READ ALSO
rand string in C

rand string in C

Задание такоe:

221
Как передать структуру в функцию?

Как передать структуру в функцию?

Такс, смотри, воот ссылки полезные для тебя 1,2

240
Как запустить batch file

Как запустить batch file

Есть у нас batch file, и в нем:

230