Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting input using stdin

Tags:

c++

sorting

stdin

I am writing a short program to sort an array of integers. I am having trouble opening my input file which is "prog1.d". The assignment has asked to create a symbolic link in the programs directory, and I after creating the object & executable, we invoke the program as follows...

prog1.exe < prog1.d &> prog1.out

I know my bubble sort works correctly & efficiently because I have used my own test 'txt' file.

The assignment says:

Your program gets the random integers from stdin and puts them in an array, sorts the integers in the array in ascending order, and then displays the contents of the array on stdout.

How do I read the file using 'cin' until EOF & add the integers to my array a[] ?

Here is my code so far:

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;
}

I know that opening a stream is the wrong way to do this, I just was using it for a test 'txt' file I was using to make sure my sorting worked. The teacher said we should redirect the input to 'cin' like someone was entering integers on a keyboard.

Any help would be greatly appreciated.

like image 278
bluetickk Avatar asked Dec 21 '22 09:12

bluetickk


1 Answers

When you're using redirection on the command line, argv does not contain the redirection. Instead, the specified file simply becomes your stdin/cin. So you don't need to (and shouldn't try to) open it explicitly -- just read from the standard input, as you would read from the terminal when input isn't redirected.

like image 144
hmakholm left over Monica Avatar answered Dec 24 '22 01:12

hmakholm left over Monica