그래서 저는 C ++에서 루프와 조건문을 배우려고해서 사용자를 위해 임의의 암호를 생성하는 프로그램을 작성하기로 결정했습니다. 어떤 이유로이 코드는 1/5 번 작동하지만 나머지 시간에는 "Exited With Non-Zero Status"만 표시됩니다. 고마워, 에빈
#include <iostream>
#include <cstdlib>
#include <chrono>
#include <thread>
#include <time.h>
using namespace std;
int main()
{
using namespace std::this_thread;
using namespace std::chrono;
// Vars
string lett;
int input;
string password("");
string lettArray [] = {"a", "b", "c", "d", "e","f", "g", "h", "i", "j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
// Prompt
cout << "How long would you like your password to be?";
cin >> input;
// Loop
for(int i = 0; i < input; i++)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
srand((time_t)ts.tv_nsec);
int random = (rand() % 26 + 1);
lett = lettArray[random];
password = password + lett;
sleep_for(milliseconds(10));
cout << "." << endl;
if (random == 0 )
break;
}
// Output
cout << password << endl;
return 0;
}
이 프로그램이 무작위로 실패하는 이유는 (의도 한 말장난) C-array를 사용하고 있으며 인덱스 범위가 잘못 되었기 때문입니다.
lettArray와 같은 C 배열은 배열 경계 위반 여부를 확인하지 않습니다. 귀하의 예 에서이 프로그램을 실행하면 해당 메모리 주소에 요소 lettArray[26]
가 없기 때문에 세그먼트 오류가 발생 string
합니다. C-array는 경계를 확인하지 않으므로 무엇이 잘못되었는지 파악하기 어려울 수 있습니다. 이것은 복잡한 프로그램에서 특히 까다로울 수 있습니다. 그 메모리 주소에 무언가가 발생하면 무의미한 결과를 얻을 수 있기 때문입니다.
더 나은 구현은 다음을 사용하는 것입니다 std::vector
.
#include <iostream>
#include <cstdlib>
#include <chrono>
#include <thread>
#include <time.h>
#include <vector>
using namespace std;
int main()
{
// You don't need these two lines
//using namespace std::this_thread;
//using namespace std::chrono;
// Vars
string lett;
int input;
string password("");
// Vector index range: 0-25
vector<string> lettArray = {"a", "b", "c", "d", "e","f", "g", "h", "i", "j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
// You only need to initialise the seed once.
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
srand((time_t)ts.tv_nsec);
// Prompt
cout << "How long would you like your password to be?";
cin >> input;
// Loop
for(int i = 0; i < input; i++)
{
int random = (rand() % 26 ); // You get results between 0-25
// Using lettArray.at(26) will result in a crash with a clear
// message that bounds are violated
lett = lettArray.at(random);
password = password + lett;
cout << "." << endl;
// Don't see a reason for this if statement
// if (random == 0 ){
// continue;
//}
}
// Output
cout << password << endl;
return 0;
}
또한 무작위 시드를 루프 외부로 옮겼으며 (한 번만 필요함) 10 밀리 초 동안 일시 중지 할 이유도 없습니다. 결과가 상관없이 적절하게 무작위 화되는 것을 볼 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다