Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/147.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用输入重定向,如何在C中读取文件和获取字符串?_C++ - Fatal编程技术网

C++ 使用输入重定向,如何在C中读取文件和获取字符串?

C++ 使用输入重定向,如何在C中读取文件和获取字符串?,c++,C++,我有一个文件,我想让我的程序从命令行使用输入重定向读取。例如,a.out

我有一个文件,我想让我的程序从命令行使用输入重定向读取。例如,
a.out
。然后我将使用
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());
}

您可以直接使用,它是与
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);
}
#包括
int main()
{
字符c;
while(std::cin.get(c))
{

std::cout您使用的
!infle.eof()
是错误的。如果文件被重定向为stdin输入,则不必打开该文件。当前您正在尝试从
cin
读取文件名。只需读取实际内容:
char c;while(cin.get(c)){…}
这在尝试读取字符后立即测试EOF,这是需要执行的操作。上面的
get()
重载返回一个
istream&
,当EOF或任何其他读取错误发生时,该istream将计算为false。我猜这也行得通。
while(cin.good(c)){(cin.get(c))…}