Моя программа продолжает выполнять цикл в первом цикле do … while, даже когда условие не выполнено

#c #windows #loops #shared-libraries

#c #Windows #циклы #общие библиотеки

Вопрос:

Я начал изучать C 3 дня назад, и после некоторых экспериментов с циклами и вектором я решил сделать с ним что-то действительно полезное: менеджер учетных записей.

Дело в том, что я использую цикл do … while для первого действия в моей программе (которое добавляет новый веб-сайт), однако после этого момента цикл не завершается, даже если условие больше не выполняется.

Я пытался отлаживать его в течение добрых 30 минут и не нашел ничего странного.

Вот код:

 #include <iostream>
#include <string>
#include <vector>


using namespace std;
int main()
{
    /*Introduction
    //Ask whether the user(me) wants to open an account already created, add a new one, or remove an existing one
    To show credentials a master password is required
    I need something that can:
        1. Find the place where credentials are supposed to be filled
        2. Enter them efficiently
        3. Bonus : Submit the data on the website and automatically connect*/


    int userAction; // Variable de sélection de la première action
    string siteNameVar("site"), urlVar("url"), userNameVar("username"), passwordVar("pass") ; 
    char sureVerification;

    vector<string> siteName(0); // Vectors containing respectively : "The sites names"
    vector<string> url(0); // Vectors containing respectively : "The sites urls"
    vector<string> userName(0); // Vectors containing respectively : "The  usernames"
    vector<string> password(0); // Vectors containing respectively : "The  passwords"



    cout << "What will you do?" << endl;

    cout << "1. Add a website account" << endl
         << "2. Connect to an existing account" << endl
         << "3. Delete an account"<< endl;

    cin >> userAction; // This is where the user enter his choice

    switch (userAction){
        case 1: // Add a new element in the vectors


           do{
                //Site Name
                do{
                    cout << "Enter the site's name (or how you want to call it)" << endl;
                    cin >> siteNameVar;
                    cout << "Are you sure? 1 = yes | Anything else = no" << endl;
                    cin >> sureVerification;
                }
                while (sureVerification != 1);




                //Site's Url
                do{
                    cout << "Enter the site's login page url" << endl;
                    cin >> urlVar;
                    cout << "Are you sure? 1 = yes | Anything else = no" << endl;
                    cin >> sureVerification;
                }

                while(sureVerification != 1);
                url.push_back(urlVar);

                // Username
                do{
                    cout << "Enter your account's username" << endl;
                    cin >> userNameVar;
                    cout << "Are you sure? 1 = yes | Anything else = no" << endl;
                    cin >> sureVerification;
                }

                while(sureVerification != 1);
                userName.push_back(userNameVar);

                // Password
                do{
                    cout << "Enter your account's password" << endl;
                    cin >> passwordVar;
                    cout << "Are you sure? 1 = yes | Anything else = no" << endl;
                    cin >> sureVerification;
                }

                while(sureVerification != 1);
                password.push_back(passwordVar);

                //Display Everything

                cout << "So the site's name is :" << siteName.back() << endl 
                     << "The login page url is :" << url.back() << endl 
                     << "Your account's username is :" << userName.back() << endl 
                     << "And your password is :" << password.back() << endl;

                //Last verification
                cout << "Is everything alright? 1 = yes | Anything else = no" << endl;
                cin >> sureVerification;
            }
            while(sureVerification != 1);




            cin.get();

            break;
        case 2: // Connect to an existing account
            cout << "display map element names" << endl;
            break;

        case 3: // Delete an account
            cout << "display map element names2" <<endl;
            break;



    } // End of the choice sequence

    cin.get();
    return 0;

}
  

Комментарии:

1. Разместите весь соответствующий код здесь непосредственно в виде текста.

Ответ №1:

Вам следует попробовать очистить входной буфер. Используйте cin.clear() и cin.ignore() перед чтением введенных пользователем данных (например. перед cin >> Верификацией)

Комментарии:

1. Большое спасибо за быстрый ответ. Я пытался добавить функцию cin.clear() ранее (cin >> Верификация), но проблема остается, независимо от значения верификации цикл не завершается.

2. Я не понимал, что верификация — это символ. Вы пробовали верификацию!= «1»? Вы должны добавить кавычки, если это переменная char

Ответ №2:

(Опубликовано от имени автора вопроса).

Вау, после сравнения более ранней версии моего кода с кодом, который я опубликовал, и замены фрагмента старого кода на новый (который «странно» сработал), я понял, что проблема была связана с тем, что типом значения для верификации (прочитайте код, чтобы понять) был char, а в выражении проверки я написал 1 (что было эквивалентно «Yes» в виде int.

Проблема решена!