2017-10-11 31 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,谢谢,修正 –