我在這裏編碼的最後一部分存在問題。 //將文件從infile複製到outfile。該程序傳輸我的infile,它只是一個8位數的編號,20392207,使用.at方法將它分成單獨的數字;並應該將該輸出保存到outfile中。我不知道如何將輸出保存到outfile。有什麼建議?將已編輯的infile文件保存到C++的輸出文件中問題
INFILE如下所示
20392207
程序的輸出看起來像這樣
The input number :20392207
The number 1:2
The number 2:0
The number 3:3
The number 4:9
The number 5:2
The number 6:2
The number 7:0
The number 8:7
了outfile應該看起來像節目出來放,而是看起來就像infile中的精確副本。
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<cmath>
using namespace std;
int main()
{
string ifilename, ofilename, line, line2;
ifstream inFile, checkOutFile;
ofstream outFile;
char response;
int i;
// Input file
cout << "Please enter the name of the file you wish to open : ";
cin >> ifilename;
inFile.open(ifilename.c_str());
if (inFile.fail())
{
cout << "The file " << ifilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Output file
cout << "Please enter the name of the file you wish to write : ";
cin >> ofilename;
checkOutFile.open(ofilename.c_str());
if (!checkOutFile.fail())
{
cout << "A file " << ofilename << " exists.\nDo you want to continue and overwrite it? (y/n) : ";
cin >> response;
if (tolower(response) == 'n')
{
cout << "The existing file will not be overwritten. " << endl;
exit(1);
}
}
outFile.open(ofilename.c_str());
if (outFile.fail())
{
cout << "The file " << ofilename << " was not successfully opened." << endl;
cout << "Please check the path and name of the file. " << endl;
exit(1);
}
else
{
cout << "The file is successfully opened." << endl;
}
// Copy file contents from inFile to outFile
while (getline(inFile, line))
{
cout << "The input number :" << line << endl;
for (i = 0; i < 8; i++)
{
cout << "The number " << i + 1 << ":";
cout << line.at(i);
cout << endl;
}
outFile << line << endl;
}
// Close files
inFile.close();
outFile.close();
} // main
題外話:'exit'是一個C++程序使用一個非常危險的事情。程序立即退出並且不會清理所有內容。在這裏你可能不會有問題,但是你可以很容易地阻塞資源並將它們打開並鎖定。 – user4581301
我將在未來編寫的程序中注意到這一點。謝謝。 –