无法将循环的输出写入文件

Can't write the output of a loop to a file

你好,我正在编写一个非常基本的密码生成器,我想使用 ofstream 将循环的输出写入一个文件。我的想法是每次循环运行时从数组 abc 输出一个人声。我不知道如何让它工作和观察。有更好的方法。

#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <fstream>


using namespace std;

int main(){

    srand(time(0));

    cout << "You'r PW is: \t" << endl;
    char abc [] {'A', 'a', 'B' ,'b', 'C', 'c', 'D', 'd', 'E', 'e', 'F', 'f', 'G', 'g', 'H', 'h', 'I', 'i', 'J', 'j', 'K', 'k', 'L', 'l', 'M', 'm', 'N', 'n', 'O', 'o', 'P', 'p', 'Q', 'q', 'R', 'r', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', 'W', 'x', 'Y', 'y', 'Z', 'z'};

    for(int i = 0; i <15; i++){
        int randomNum =  rand() % 53;
        cout << abc[randomNum];
        ofstream fob;
        fob.open("contr.txt");
        fob << abc[randomNum];
    }
}

顺便说一下,我得到的字符如“,”和“->”不在我的数组中。

不得不搬家

ofstream fob;
fob.open("contr.txt");

跳出循环。现在你在每次迭代时重写文件。

这里的问题很简单,有两种解决方法。 您的程序所做的是在循环的每次迭代中创建并打开一个新流到文件,但默认情况下 ofstream 会覆盖它打开的文件,因此您可以将打开的流移出循环(更好的方法) 或添加标志 ios::app 作为流开启器的第二个参数,以便附加您正在输出的内容。

此外,您应该使用 int randomNum = rand() % 52;。 在集合 {0, 1, 2, ... 51} 中选择一个数字,假设您忘记将 'X' 放入数组中,这将是您数组的所有可能索引之一。