【问题标题】:Why isn't my loop writing into the txt file?为什么我的循环没有写入 txt 文件?
【发布时间】:2018-04-23 00:56:36
【问题描述】:

我正在尝试将循环写入文本文件,但它一直将其写入控制台并将 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;

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

【问题讨论】:

  • but it keeps writing it into the console你确定吗?
  • 该代码不会写在任何地方!请发布完整代码,但由于您没有将myfile 作为参数传递给Crack(),因此无法将任何内容写入您的文件。
  • 编辑您的问题以包含minimal reproducible example
  • 说真的,将向量初始化为您想要的字符而不是编写循环更容易。
  • 是的。仅仅打开一个文件并不会神奇地将cout 链接到文件而不是控制台。

标签: c++ file


【解决方案1】:

这是对这个问题的递归处理,它可能更简单,您可以适应。值得注意的是,无论你选择哪种方法,这个问题都需要检查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);
}

【讨论】:

    猜你喜欢
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2019-11-09
    相关资源
    最近更新 更多