0

我有一个文件,我希望我的程序从命令行使用输入重定向读取该文件。例如,a.out < file.dat。然后我打算使用cin.get()并将字符放入一个数组中。

我不想硬编码任何输入文件名,我在一些现有的帖子中已经看到了。如果我将此输入重定向视为stdin,我是否必须显式打开我的文件?

int main (int argc, char *argv[])
{

  string filename;
  ifstream infile;

  cin >> filename;  

  do {               

  int c = 0; 
  c = infile.get();  //need to get one character at a time
                     //further process


} while ( ! infile.eof());

}

4

1 回答 1

1

您可以只使用cin,它是与关联的流缓冲区stdin

#include <iostream>

int main()
{
    char c;
    while (std::cin.get(c))
    {
        std::cout << c << std::endl; // will print out each character on a new line
    }
    exit(0);
}
于 2012-11-26T06:51:40.093 回答