如何让输入文件进入数组

How to get input file to go into an array

本文关键字:数组 文件 输入      更新时间:2023-10-16

我正在尝试将输入文件中的信息获取到输出文件中,我已经这样做了,但是我不知道如何将文件中的数字获取到数组中,并且只能输出可被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

我会用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();
}