阅读管道stdin和用户输入

时间:2013-10-25 04:52:38

标签: c++ file-io stdin

我正在编写一个用于读取空格分隔文件的c ++数据结构类的程序,我编写了一个小函数,以便我可以管理不同的文件并使用它们,但我还想接受用户输入使用cin,似乎缓冲区只是循环。我有点超出我的深度,但这是我的输入功能。我正在通过$ cat filename运行程序./compiledexec。我希望有人可能知道为什么在其他地方使用cin不等待用户输入并且可能有助于解决方案?

    void catchPipe(int dataArray[][9]);
    int main(){
        int inArray[9][9];
        int column;
        catchPipe(inArray);

        cout << "Which column would you like to check?";
        cin >> column;  // This input is skipped totally.
        functionChecksIfInCol(column);  //Function  called with garbage value
        cout << "end program" << endl;
        return 0;
    }

    void catchPipe(int dataArray[][9]){
        int i;
        int n=0;
        int pos=0;
        string mystring;
        while(cin){
            getline(cin, mystring);
            if( n < 9 ){
                for(i = 0; i < mystring.length(); i++){
                    if( (int)mystring[i] != 32 ){
                        dataArray[n][pos] = mystring[i] - '0';
                        pos++;
                    }   
                }pos =0; 
            ++n;
            }   
        }   
    }// end catchPipe()
     //Sample File input:     
    0 8 0 1 7 0 0 0 3   
    0 2 0 0 0 0 0 0 9   
    0 9 0 0 3 0 5 4 8   
    0 0 4 0 9 0 0 0 0   
    0 0 0 7 0 3 0 0 0   
    0 0 0 0 1 0 4 0 0   
    6 1 9 0 8 0 0 5 0   
    7 0 0 0 0 0 0 8 0   
    2 0 0 0 6 4 0 1 0  

谢谢!

该程序填写了我的inArray,但它跳过了下一个cin的调用。我假设这是因为stdin已经从键盘重定向到linux的管道?也许我可以声明另一个istream对象并将其指向键盘或其他东西?我不知道该怎么做

1 个答案:

答案 0 :(得分:0)

使用矢量:

void cachePipe(std::vector<std::vector<int>> data)
{
    std::string line;
    while (std::getline(std::cin, line))
    {
        std::istringstream iss(line);
        std::vector<int> fill((std::istream_iterator<int>(line)),
                            std::istream_iterator<int>());
        data.push_back(fill);
    }
}