문제

I have just started C++ and have some experience with C# so I have some programming experience in general. However, seems like straight away I have been shot down. I have tried looking on Google so not to waste anyone's time to no avail.

int main(int argc, char *argv[])
{
    HANDLE  hConsole;
    int k = 5;
    string h;
    string password = "pass";

    hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, k);
    SetConsoleTextAttribute( GetStdHandle( STD_INPUT_HANDLE ), 0x5B );

    while (h != password)
    {
        printf("This PC is locked\nEnter the password to gain access\n");
        scanf("%s", &h);
    }

    printf("\n");
    system("PAUSE");
    return EXIT_SUCCESS;
}

Whenever I run this it will get me to enter the password and when I click enter it will acknowledge and then crash asking me to either debug or send information to Microsoft. This started when I added the while loop checking two strings. Have I executed this correctly or have I missed something?

Just in case its not clear. I want the program to compare a string with an input and if they are both the same the program will end.

Thanks for looking.

도움이 되었습니까?

해결책

You simply cannot use scanf() to read into std::string. This is because scanf() is part of C API and it does not support non-POD types. There, %s format specifier expects a pointer to character array with size enough to hold the value (which you cannot really guarantee and that's why scanf() is even considered harmful) whereas you pass it a pointer to object of type std::string (which is far, far different from a plain array). A good compiler would even issue a warning in this case (if not an error, because non-POD types cannot be passed through va_list). Why don't you read into a character array (the C way), or use std::cin instead like std::cin >> h;?

다른 팁

As chris suggested, this program can be simplified by using the correct functions:

#include <iostream>
#include <string>

int main()
{
    std::string password = "pass", input;

    do
    {
        std::cout << "This computer is locked."
                  << "Enter the password to gain access: ";
        std::cin >> input;
    } while (input != password);

    std::cout << "Welcome!" << std::endl;
    system("PAUSE");

    return 0;
}

1/ As many beginners in C++, you are actually writing C code. Look for documentation about input/ouput in C++.

2/ How do you compile your code? Your error should have been caught by the compiler

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top