簡體   English   中英

使用stdin重定向輸入

[英]Redirecting input using stdin

我正在寫一個簡短的程序來排序整數數組。 我無法打開輸入文件“prog1.d”。 分配要求在程序目錄中創建一個符號鏈接,在創建對象和可執行文件后,我們按如下方式調用程序...

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

我知道我的冒泡排序正常有效,因為我使用了自己的測試'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;
}

我知道打開一個流是錯誤的方法,我只是用它來測試'txt'文件我用來確保我的排序工作。 老師說我們應該將輸入重定向到'cin',就像有人在鍵盤上輸入整數一樣。

任何幫助將不勝感激。

當您在命令行上使用重定向時, argv不包含重定向。 相反,指定的文件只是你的stdin / cin 因此,您不需要(也不應該嘗試)明確地打開它 - 只需從標准輸入讀取,就像在未重定向輸入時從終端讀取一樣。

由於您在stdin上管道文件,因此在argv [1]上沒有文件名,只需在用戶在控制台上鍵入時讀取stdin,例如使用cin

cin.getline (...);

其他答案是完全正確的,但這里是重寫的代碼:

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

    // read int's & place into array a[]
    //ALWAYS check the boundries of arrays
    for(int i=0; i<SIZE; i++) 
    {
        std::cin >> a[i];
        if (std::cin)
            count = count + 1;
        else
            break;
    }

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

    return 0;
}

正如大家所說,直接使用std::cin - 你不需要打開輸入文件,你的shell已經為你完成了。

但是,拜托,拜托,請不要使用cin.eof()來測試你是否已經達到輸入的最后。 如果您的輸入有缺陷,您的程序將掛起。 即使您的輸入沒有缺陷,您的程序可能(但不一定)會再次運行循環。

試試這個循環:

int a[SIZE];
int i = 0;
while( std::cin >> a[i]) {
  ++i;
}

或者,使用將自動增長的std::vector添加健壯性:

std::vector<int> a;
int i;
while(std::cin >> i) {
  a.push_back(i);
}

或者,使用通用算法:

#include <iterator>
#include <algorithm>
...
std::vector<int> a;
std::copy(std::istream_iterator<int>(std::cin),
          std::istream_iterator<int>(),
          std::back_inserter(a));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM