为了获得更快的输入,我看到您可以执行file-redirection,并包含一个已经设置了cin输入的文件。
从理论上讲,它的使用应如下所示:
App.exe inputfile outputfile据我从C++入门书中了解到,下面的C++ code1应该读取文本文件中的cin输入,而不需要任何其他特殊指示like2
2
include <fstream>
ofstream myfile;
myfile.open ();1以下C++代码..。
#include <iostream>
int main()
{
    int val;
    std::cin >> val; //this value should be read automatically for inputfile
    std::cout << val;
    return 0;
}我是不是遗漏了什么?
发布于 2013-08-06 13:28:25
要使用代码1,您必须像这样调用您的程序:
App.exe < inputfile > outputfile您还可以使用:
App.exe < inputfile >> outputfile在这种情况下,输出不会用命令的每次运行来重写,但是输出将被附加到已经存在的文件中。
有关在Windows中重定向输入和输出的更多信息,您可以找到这里。
请注意,<、>和>>符号将逐字输入--它们不只是用于本解释中的表示目的。因此,例如:
App.exe < file1 >> file2发布于 2013-08-06 13:54:04
除了原来的重定向,>/ >>和<
您也可以重定向std::cin和std::cout。
如下所示:
int main()
{
    // Save original std::cin, std::cout
    std::streambuf *coutbuf = std::cout.rdbuf();
    std::streambuf *cinbuf = std::cin.rdbuf(); 
    std::ofstream out("outfile.txt");
    std::ifstream in("infile.txt");
    //Read from infile.txt using std::cin
    std::cin.rdbuf(in.rdbuf());
    //Write to outfile.txt through std::cout 
    std::cout.rdbuf(out.rdbuf());   
    std::string test;
    std::cin >> test;           //from infile.txt
    std::cout << test << "  "; //to outfile.txt
    //Restore back.
    std::cin.rdbuf(cinbuf);   
    std::cout.rdbuf(coutbuf); 
}发布于 2013-08-06 14:13:21
我只是在解释有关的命令行参数。
您可以将文件名作为命令行输入提供给可执行文件,但随后需要在代码中打开它们。
喜欢
您提供了两个命令行参数,即inputfile & outputfile。
App.exe inputfile outputfile
现在在你的代码中
#include<iostream>
#include<fstream>
#include<string>
int main(int argc, char * argv[])
{
   //argv[0] := A.exe
   //argv[1] := inputFile
   //argv[2] := outputFile
   std::ifstream vInFile(argv[1],std::ios::in); 
   // notice I have given first command line argument as file name
   std::ofstream vOutFile(argv[2],std::ios::out | std::ios::app);
   // notice I have given second command line argument as file name
   if (vInFile.is_open())
   {
     std::string line;
     getline (vInFile,line); //Fixing it as per the comment made by MSalters
     while ( vInFile.good() )
     {
         vOutFile << line << std::endl;
         getline (vInFile,line);          
     }
     vInFile.close();
     vOutFile.close();
  }
  else std::cout << "Unable to open file";
  return 0;
}https://stackoverflow.com/questions/18081565
复制相似问题