为什么我的循环写入txt文件?

时间:2018-04-23 00:56:37

标签: c++ file

我正在尝试将我的循环写入文本文件,但它会将其写入控制台并将txt文件留空。

#include <iostream>
#include <vector>
#include <string.h>
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;
void Crack(string password, vector<char> Chars)
{
    cout<<"PASSWORD TO CRACK: "<<password<<endl;
    int n = Chars.size();
    int i = 0;
    while(true)
        {
            i++;
            int N = 1;
            for(int j=0;j<i;j++)N*=n;
            for(int j=0;j<N;j++)
                {
                    int K = 1;
                    string crack = "";
                    for(int k=0;k<i;k++)
                        {
                            crack += Chars[j/K%n];
                            K *= n;
                        }
                    cout<< "Testing PASS: "<<crack<<" "<<"against "    <<password<<endl;
                    if(password.compare(crack) == 0){
                    cout<<"Cracked password: "<<crack<<endl;
                    return;
                    }
                }
        }
}
int main()
{
    ofstream myfile;
    myfile.open ("pass.txt");


    vector<char> Chars;
    for(char c = '0';c<='z';c++){
    if(islower(c) || isdigit(c))Chars.push_back(c);
    }
    Crack("zzzzzzzzzzzzzzzzzz", Chars);

myfile.close();
}

添加了完整的代码 我希望它将每个输入写入文本文档的新行,但无论我在哪里尝试添加

  myfile << c;

它给了我奇怪的输出并且没有写入文本文件

1 个答案:

答案 0 :(得分:0)

这是对问题的递归看法,可能更简单,您可以适应。值得注意的是,无论您选择哪种方法,此问题都需要检查26 ** 18个不同的密码,这需要很长时间。也许可以用更短的密码试试。

#include <iostream>
#include <fstream>
using namespace std;

ofstream myfile("pass.txt");

void Crack(string password, string crack, string buffer)
{
    if (crack.size() == password.size()){
        myfile << "Testing PASS: " << crack << " " << "against " << password << endl;
        if (password.compare(crack) == 0){
            myfile << "Cracked password: " << crack << endl;
        }
    }
    else{
        for (int i = 0; i < buffer.size(); i++){
          Crack(password, crack+buffer[i], buffer);
        }
    }
}

int main()
{
    string Chars = "";
    for(char c = '0';c<='z';c++){
        if(islower(c) || isdigit(c))
            Chars+=c;
    }
    Crack("zzzzz","", Chars);
}