2013-10-25 85 views
0

我正在写一个程序读取一个空格分隔的文件的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。我假设这是因为标准输入已经从键盘重定向到从Linux管道?也许我可以声明另一个istream对象并将其指向键盘或其他东西?我不知道在这里做什么

回答

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); 
    } 
} 
+0

这将如何让我重用CIN程序中的键盘输入?我遇到的问题是任何后来的cin调用都会被跳过,而不是要求用户输入。 – Matt

+0

@Matt你能告诉我一个'cin'给你的这种行为的例子吗?它可能只是一个流状态标志打开。在任何后续输入操作之前尝试执行'cin.clear()'。 – 0x499602D2

+0

我做了一个cin.clear()。我真的不能举一个例子,但它基本上跳过我的其他cin调用。我会在我的帖子中加入更多的代码,让你了解程序的功能。我基本上用来自linux管道的字符串输入填充二维int数组。 – Matt