使用stdin重定向输入

blu*_*ckk 4 c++ sorting stdin

我正在写一个简短的程序来排序整数数组.我无法打开输入文件"prog1.d".分配要求在程序目录中创建一个符号链接,在创建对象和可执行文件后,我们按如下方式调用程序...

prog1.exe < prog1.d &> prog1.out
Run Code Online (Sandbox Code Playgroud)

我知道我的冒泡排序正常有效,因为我使用了自己的测试'txt'文件.

作业说:

你的程序从stdin获取随机整数并将它们放在一个数组中,按升序对数组中的整数进行排序,然后在stdout上显示数组的内容.

如何使用'cin'读取文件直到EOF并将整数添加到我的数组a []?

到目前为止,这是我的代码:

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

    for ( int i=1; i<argc; i++)
    {
        ifstream inFile; // declare stream
        inFile.open( argv[i] ); // open file
        // if file fails to open...
        if( inFile.fail() )
        {
            cout << "The file has failed to open";
            exit(-1);
        }
        // read int's & place into array a[]
        for(int i=0; !inFile.eof(); i++)
        {
            inFile >> a[i];
        }
        inFile.close(); // close file
    }

    bubbleSort(a); // call sort routine
    printArr(a); // call print routine

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我知道打开一个流是错误的方法,我只是用它来测试'txt'文件我用来确保我的排序工作.老师说我们应该将输入重定向到'cin',就像有人在键盘上输入整数一样.

任何帮助将不胜感激.

Hen*_*olm 5

在命令行上使用重定向时,argv不包含重定向.相反,指定的文件只是你的stdin/ cin.因此,您不需要(也不应该尝试)明确地打开它 - 只需从标准输入读取,就像在未重定向输入时从终端读取一样.