C ++ - Проверка строковых данных структуры с введенными пользователем строковыми данными (бесконечное число do, пока l oop) - PullRequest
0 голосов
/ 27 мая 2020

Как видно из заголовка, я хочу «сравнить» строку, введенную пользователем, со строкой, прочитанной из файла. Я использовал тип данных struct для чтения данных из файлов.

Вот входной файл

Samed Skulj Stomatolog
Adin Vrbic Hirurg
Ahmed Skulj Psihijatar

До того, как мы go столкнулись с проблемой, вот код

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

struct dataAboutDoctors
{
    string name;
    string surname;
    string profession;
};

int main(int argc, char** argv) 
{
    ifstream readingDoctors;
    readingDoctors.open("citanjedoktora.txt");
    if (readingDoctors.fail())
    {
        cout << "Ne postojeca datoteka";
        exit(1);
    }

    dataAboutDoctors doctors[100];
    int numbersOfDoctors = 0;

    while(readingDoctors >> doctors[numbersOfDoctors].name >> doctors[numbersOfDoctors].surname >> doctors[numbersOfDoctors].profession)
    {
        numbersOfDoctors++;
    }
    cout << "----- Name of doctors and their professions -----" << endl;
    cout << "---------------------------------------------" << endl;
    string temp1,temp2;
    for (int i = 0; i < numbersOfDoctors; i++)
    {
        cout << "Name of " << i+1 <<". doctor: " << doctors[i].name << endl;
        cout << "Surname of " << i+1 <<". doctor: " << doctors[i].surname << endl;
        cout << "Profession of " << i+1 <<". doctor: " << doctors[i].profession << endl;
        cout << "------------------------------------------" << endl;
        temp1+=doctors[i].name;
        temp2+=doctors[i].surname;
        cout << endl;
    }
    string name1,surname1;
    cout << "Enter the name of doctor you see: ";
    cin >> name1;
    cout << "Enter the surname of doctor you see: ";
    cin >> surname1;
    do
    {
    if (name1 != temp1 || surname1 != temp2)
    {
        cout << "There is no name nor surname of the doctor you have entered. Enter again: ";
        cin >> name1 >> surname1;
    }
    }while(name1 != temp1 || surname1 != temp2);

    return 0;
}

Когда пользователь вводит имя врача и фамилию, и если это ПРАВИЛЬНЫЕ имя и фамилия, программа должна продолжить выполнение других действий, но в этом случае или примере вы не можете увидеть другую часть программы, потому что она не такая, как важно.

Вот консольный ввод

----- Name of doctors and their professions -----
---------------------------------------------
Name of 1. doctor: Samed
Surname of 1. doctor: Skulj
Profession of 1. doctor: Stomatolog
------------------------------------------

Name of 2. doctor: Adin
Surname of 2. doctor: Vrbic
Profession of 2. doctor: Hirurg
------------------------------------------

Name of 3. doctor: Ahmed
Surname of 3. doctor: Skulj
Profession of 3. doctor: Psihijatar
------------------------------------------

Enter the name of doctor you see:

Enter the name of doctor you see: это основная проблема. Когда пользователь вводит даже правильное имя, он снова просит пользователя ввести имя и фамилию и снова, и снова. Итак, как вы можете видеть, мне удалось сделать бесконечное l oop.

Мой вопрос в том, как так называемое "сравнение" введенной пользователем строки и строки, прочитанной из файла .txt? PS: Я новичок в C ++, извините, если это глупый вопрос. Заранее спасибо

1 Ответ

0 голосов
/ 27 мая 2020

В for l oop

string temp1,temp2;
for (int i = 0; i < numbersOfDoctors; i++)
{
    // ...
    temp1+=doctors[i].name;
    temp2+=doctors[i].surname;
}

вы накапливаете имена и фамилии в одной строке даже без пробелов.

Итак, это l oop

do
{
if (name1 != temp1 || surname1 != temp2)
{
    cout << "There is no name nor surname of the doctor you have entered. Enter again: ";
    cin >> name1 >> surname1;
}
}while(name1 != temp1 || surname1 != temp2);

никогда не прерывает свои итерации, пока вы не введете строку, которая будет содержать все имена и фамилию в виде отдельных строк.

Возможно, вам нужно изменить условие в операторе if и в l oop на

( temp1.find( name1 ) == std::string::npos || temp2.find( surname1 ) == std::string::npos )

И логически относительно используемого условия в операторе if сообщение должно выглядеть так:

"There is no name or surname of the doctor you have entered. Enter again: "
                 ^^^

На самом деле использование переменных temp1 и temp2 не имеет смысла. . Вы должны удалить их. Эта часть программы может выглядеть следующим образом:

#include <algorithm> // this header is required for using std::find_if

//...

string name1,surname1;
cout << "Enter the name of doctor you see: ";
cin >> name1;
cout << "Enter the surname of doctor you see: ";
cin >> surname1;

bool success = false;
do
{
    success = std::find_if( doctors, doctors + numbersOfDoctors,
                            [&]( const auto &d )
                            {
                                return d.name == name1 && d.surname == surname1;
                            } ) != doctors + numbersOfDoctors;

    if ( not success )
    {
        cout << "There is no name or surname of the doctor you have entered. Enter again: ";
        cin >> name1 >> surname1;
    }
} while( not success );

Вот демонстрационная программа.

#include <iostream>
#include <string>
#include <algorithm>

struct dataAboutDoctors
{
    std::string name;
    std::string surname;
    std::string profession;
};

int main() 
{
    const size_t N = 100;
    dataAboutDoctors doctors[N] =
    {
        { "Samed", "Skulj", "Stomatolog" },
        { "Adin",  "Vrbic", "Hirurg" },
        { "Ahmed", "Skulj", "Psihijatar" }  
    };

    size_t numbersOfDoctors = 3;

    std::string name1, surname1;

    std::cout << "Enter the name of doctor you see: ";
    std::cin >> name1;
    std::cout << "Enter the surname of doctor you see: ";
    std::cin >> surname1;

    bool success = false;
    do
    {
        success = std::find_if( doctors, doctors + numbersOfDoctors,
                            [&]( const auto &d )
                            {
                                return d.name == name1 && d.surname == surname1;
                            } ) != doctors + numbersOfDoctors;

        if ( not success )
        {
            std::cout << "There is no name or surname of the doctor you have entered. Enter again: ";
            std::cin >> name1 >> surname1;
        }   
    } while( not success ); 

    return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...