问题描述
这是代码:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <windows.h>
using namespace std;
const char alphanum[] = "0123456789!@#$%^&*abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMnopQRSTUVWXYZ";
int string_length = sizeof(alphanum)-1;
int main()
{
system("Color 0A");
int n;
cout<<"Quanto deve essere lunga la password? "; // Here it's asking me the length of the password
cin>>n;
srand(time(0));
for(int i=0; i<n; i++)
cout << alphanum[rand() % string_length];
ofstream fout("password.txt");
cout <<""<<endl; // Here I need the variable to write the password in the text file
fout.close();
fout<<"Grazie comunque"<<endl;
return 0;
}
也许这是一个愚蠢的问题,但是我才开始编码。
解决方法
您需要在循环内移动密码编写代码
ofstream fout("password.txt");
for(int i=0; i<n; i++)
{
char password_char = alphanum[rand() % string_length];
cout << password_char;
fout << password_char;
}
fout << endl;
fout.close();
与您写入cout
的代码完全相同。