0

パスワードが正しく入力されているかどうかをチェックできるようにするプログラムを、テック キャンパーの 1 人が作成するのを手伝いたいと考えています。これについては限られた知識しかありません。ご協力いただけると幸いです。ありがとうございました。

//This lets the user input a password to enter an area

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Please enter the password";
     char* userData;
    do 
    {
        cin.getline(userData, 70);
            //says the data back
        cout << userData;
    }while (userData != '\n');

    if (userData == 'This is my password')
    {
        cout << "Welcome back";
    }
    else 
    {
        while(userData != 'This is my password');
        cout << "******** INTRUDER ALERT *********";
    }

    return 0;
}
4

1 に答える 1

1

あなたのコードには多くの問題があります。まず、おそらく do~while ループにパスワード チェック条件も含める必要があります。そうしないと、ユーザーが空白行に入力した後にのみパスワードをチェックします (パスワードが文字通り空白行の場合にのみパスワードと一致します)。 . cin.getline() はユーザーに文字列の入力を求めるため、次の行はユーザーが文字列を入力した後にのみ実行されます。

C++ での文字列比較は、'==' 演算子を使用して行うことはできません。これは意図した効果がありません。あなたの場合の「==」演算子は、文字列の最初の文字とそれだけでASCII文字コードチェックを文字通り実行します。文字列比較を行いたい場合は、相違がない場合に 0 を返す strcmp() などの比較関数を使用する必要があります。

また、文字列変数に使用するメモリを割り当てていません。これは、C++ では大したことではありません。多くのスクリプト言語ではこれは必要ありませんが、C++ の文字列は、使用する前に必要なサイズに事前に割り当てる必要があります。

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "Please enter the password";
    char userData[71];   // I've allocated 71 characters to this string, which matches the amount of characters you accept in your getline call (plus one more for the required end of string character '\0').
    do 
    {
        cin.getline(userData, 70);
            //says the data back
        cout << userData;

        // Notice, I've moved this block inside the loop, as it needs to be tested after each password entry rather than after the user has input an empty line.
        if (!strcmp(userData, "This is my password")) // I've changed this statement to use the strcmp function to actually compare the values of the entire strings together.  The result of this function is the total number of differences found, so if it returns 0 that means the strings are the same.  Also note, I am using double quotes instead of single for the password value.
        {
            cout << "Welcome back";
            break; // I've added a break here to break out of the loop when the user inputs the correct password.
        }
        else 
        {
            // Removed the infinite loop, as it has no purpose other than locking up the program.
            cout << "******** INTRUDER ALERT *********";
        }

    }while (strlen(userData) != 0); // I'm not too sure about this, but I think if you enter a blank line it does not contain the '\n' within itself.  Instead, I've opted to use the strlen() function which tells you how many letters are in the given string.

    return 0;
}
于 2013-07-10T22:00:35.200 に答える