文件处理 - 错误:与 while 循环 (C++) 中的"运算符>>"不匹配(代码::块)

file handling-the error: no match for 'operator>>' in while loop (c++)(code::block)

本文关键字:gt 运算符 代码 不匹配 C++ 错误 处理 while 文件 循环 中的      更新时间:2023-10-16

我编写了以下程序:

#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循环条件中得到以下编译错误:

与"运算符>>不匹配

据我了解,我的条件意味着如果不按照这个进入 cin 的顺序,请离开循环!!

已编辑:解决了我的问题1:数组没有运算符>>。2:可以简单地使用整数类型3:如果不得不使用数组..需要一一放..

谢谢你帮助我

你的代码几乎没问题。这本来没关系:

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

但是,operator >>无法处理整数数组(int contact[10])!所以你必须逐个 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
    }     
}

请注意,我添加了输入验证。始终验证用户输入!