我正在尝试将输入文件中的信息输入到输出文件中,我已经完成了,但我无法弄清楚如何将文件中的数字转换为数组并仅输出可被7整除的数字我已经被困了几个小时,请帮忙。
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
int main()
{
string ifilename, ofilename, line;
ifstream inFile, checkOutFile;
ofstream outFile;
char response;
// 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
char array[10];
int numberz = 0;
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))
{
fscanf(ifilename, &array[numberz]);
cout << line << endl;
outFile << line << endl;
}
// Close files
inFile.close();
outFile.close();
} // main
答案 0 :(得分:0)
我将boost::filesystem
用于该任务。
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
namespace fs = boost::filesystem;
int main()
{
fs::path ifilename;
std::cout << "Input file: ";
std::cin >> ifilename;
fs::ifstream inFile{ifilename};
if ( inFile.fail() )
throw std::invalid_argument("Could not open file");
fs::path ofilename;
std::cout << "Output file: ";
std::cin >> ofilename;
if ( fs::exists(ofilename) )
{
std::cout << ofilename << " exists. Do you want to overwrite it? (y/n) ";
char response;
std::cin >> response;
if ( ! ( response == 'y' || response == 'Y' ) )
return 1;
}
fs::ofstream outFile{ofilename};
if ( outFile.fail() )
throw std::invalid_argument("Could not open file");
std::vector<std::string> array;
std::string line;
while ( std::getline(inFile, line) )
{
array.push_back( line );
std::cout << line << '\n';
outFile << line << '\n';
}
inFile.close();
outFile.close();
}