gpt4 book ai didi

c++ - 无法使用 ifstream 打开文件

转载 作者:太空宇宙 更新时间:2023-11-04 14:29:28 42 4
gpt4 key购买 nike

我想获得有关以下代码行的一些帮助。对于函数 constructArray,我无法运行它,正如 !aFile as true 消息所示,但我不知道错误是什么。非常感谢您的帮助另外,如何使用 .txt 创建 inFile 文件名,我尝试使用 +".txt"进行缩进,但由于参数中的文件类型,我无法这样做。编译器运行图像:https://imgur.com/a/wkGwL

    using namespace std;

enum NumType {Odd, Even};

struct Number
{
int no;
NumType type;
int oddDigits;
int evenDigits;
int sumDigits;
int noDigits;
};

// Create inFile data file with certain number of integers which are randomly generated
void constructInfile (fstream& aFile, char fileName[]);


// Read data from infile txt file and transfer to array of numbers
int constructArray (fstream& aFile,const char fileName[], Number ran[]);

/*
void processArray (Number [ ], int);

// Transfer information from array and store into output file called outfile txt with specific information format
void arrayToOutfile (fstream&, char [ ], Number [ ], int);
*/


const int MAX = 50;

int main()
{
srand(time(NULL));
fstream aFile;
char fileName [MAX];

cout << "Enter designated file name to be created" << endl;
cin >> fileName;

constructInfile (aFile,fileName);

Number ran[MAX];
int recNo = constructArray(aFile,fileName,ran);
cout << recNo << " of records transferred" << endl;

}

// Create inFile data file with certain number of integers which are randomly generated
void constructInfile (fstream& aFile,char fileName[]){
aFile.open(fileName, ios::out);

if(aFile.fail()){
cout << "File open unsuccessful" << endl;
aFile.close();
exit(1);
}

cout << "Begin creation of " << fileName << " file" << endl << endl;

int size = rand()%51+50;

for(int a = 0;a < size;a++){
aFile << rand()%1000+1 << endl;
}

cout << fileName << " file successfully created" << endl;

}


// Read data from infile txt file and transfer to array of numbers
int constructArray (fstream& aFile,const char fileName[], Number ran[]){

aFile.open (fileName, ios::in);

if (!aFile)
{
cout << fileName << " failed to open" << endl;
aFile.close ();

return 0;
}

cout << "Begin from " << fileName << " to array" << endl;

int i = 0;

char tabKey;

while (aFile >> ran[i].no)
{
aFile.get (tabKey); // read and discard
i++;
}

aFile.close ();
cout << fileName << " to array done" << endl;

return i;
}

最佳答案

您在 ios::out 模式下打开了一个文件并且从未关闭过它!

您再次尝试在 ios::in 模式下打开同一个文件。如何在不正确关闭 fstream 的情况下以两种不同的模式打开文件两次?

您需要在函数 constructInfile() 中关闭文件流!!!

关于c++ - 无法使用 ifstream 打开文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47426603/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com