2017-10-11 27 views
-1

我寫了下面的程序:文件處理,錯誤:不對應的「運營商>>」在while循環(C++)(代碼::塊)

#include <iostream> 
#include <fstream> 
using namespace std; 

int main() 
{ 
    ofstream theFile("students_info.txt"); 
    cout<<"Enter the data as requested"<<endl; 
    cout<<"Press ctrl+z to exit"<<endl; 

    string name, address; 
    int contact[10]; 

    while(cin >> name >> address >> contact) { 
    theFile << "\nName: "  << name 
      << "\n Address: " << address 
      << "\nContact: " << contact[10] << endl; 
    } 

    theFile.close(); 
    return 0; 
} 

我從獲得以下編譯錯誤我while循環條件:

no match for 'operator>>'

從我所瞭解的情況來看,我的條件意味着如果不是以cin的入口順序離開循環!

編輯:解決我的問題 1:數組沒有操作符>>。 2:可以簡單地使用int類型 3:如果不得不使用數組..need把它一一..

謝謝你對我的幫助

+0

'int contact [10];'如果你想要10個整數,你需要逐一讀取它們。數組中沒有操作符>>。 – 2017-10-11 22:11:39

+0

哦!是的,它似乎現在完美的工作..但我想我的聯繫int類型...我怎麼能這樣做? – shaistha

+0

sorryjust int類型是好的...我怎麼能這個愚蠢的! – shaistha

回答

1

你的代碼幾乎是正常的。這個就OK了:

while(cin >> name >> address) { 
    .. 
} 

但是,該operator >>不能處理int數組(int contact[10])!所以,你必須通過INT INT讀它,例如:

while(cin >> name >> address >> contact[0] >> contact[1] >> ...) { 
    .. 
} 

或替換這一點:我添加輸入驗證

while(true) { 
    cin >> name; 
    if (!isValidName(name)) 
     return; // or handle otherwise 

    cin >> address; 
    if (!isValidAddress(address)) 
     return; // or handle otherwise 

    for (int i = 0; i < sizeof(contact)/sizeof(contact[0]); i++) { 
     cin >> contact[i]; 
     if (!isValidContact(contact[i]) 
      return; // or handle otherwise 
    }  
} 

通知。始終驗證用戶輸入!

+0

'contact [0] << contact [1] <<'你的意思是''' – 2017-10-11 22:39:42

+0

@ manni66,謝謝,修正 –