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對象並將其指向鍵盤或其他東西?我不知道在這裏做什麼
這將如何讓我重用CIN程序中的鍵盤輸入?我遇到的問題是任何後來的cin調用都會被跳過,而不是要求用戶輸入。 – Matt
@Matt你能告訴我一個'cin'給你的這種行爲的例子嗎?它可能只是一個流狀態標誌打開。在任何後續輸入操作之前嘗試執行'cin.clear()'。 – 0x499602D2
我做了一個cin.clear()。我真的不能舉一個例子,但它基本上跳過我的其他cin調用。我會在我的帖子中加入更多的代碼,讓你瞭解程序的功能。我基本上用來自linux管道的字符串輸入填充二維int數組。 – Matt