次のコード行について助けを求めたいと思います。 関数constructArrayの場合、私はそれを実際のメッセージとして!aFileとして表示することはできませんが、何がエラーなのかわかりません。 あなたの支援に本当に感謝します また、inFile fileNameを.txtで作成するには、 "。txt"でインデントを試しましたが、引数のファイルタイプのためにできません。 コンパイラの実行イメージ:https://imgur.com/a/wkGwLifstreamでファイルを開くことができません
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;
}
解決策で問題が解決しない場合は、ファイルが作成されているかどうかを確認し、ここにエラーメッセージを投稿してください。 –
2番目の機能のみが動作しません。 cerrを追加しようとしました<< "エラー:" << strerror(errno); !aFileのif文の場合は ですが、エラーは表示されません。 – MATU
@MATUはい2番目の関数は、最初の関数ですでに開いているので、ファイルを開くことができません。したがって、最初の関数の最後に閉じなければなりません。一般的なルールは操作後にファイルを閉じることです。そのため、第2の機能(ベストプラクティス)でファイルを閉じる必要もあります。 –