C++将文件读入数组错误:'operator >>'不匹配

问题描述:

在我的OpenFile函数中,它应该提示用户输入文件名并将文件读入数组。我不断收到错误:no match for 'operator>>' (operand types are 'std::ifstream {aka std::basic_ifstream<char>}' and 'entryType')。我做了一些研究,发现了一些与这个错误有关的类似问题。我没有找到有用的问题,因为他们写得很差。我认为问题可能是使用void函数或声明数组作为entryType的一部分。我知道我得到这个错误,因为编译器查找了一个可以处理(istream) >> (entryType)但没有找到的函数。我将如何修复我的代码以摆脱此错误?C++将文件读入数组错误:'operator >>'不匹配

头文件

include<string> 
using namespace std; 

enum Title {Mr, Mrs, Ms, Dr, NA}; 

struct NameType { 
    Title title; 
    string firstName; 
    string lastName; 
}; 

    struct AddressType { 
    string street; 
    string city; 
    string state; 
    string zip; 
}; 

struct PhoneType { 
    int areaCode; 
    int prefix; 
    int number; 
}; 

struct entryType { 
    NameType name; 
    AddressType address; 
    PhoneType phone; 
}; 

const int MAX_RECORDS = 50; 

代码

entryType bookArray[MAX_RECORDS]; // entryType declared in header file 

int main() 
{ 
    entryType userRecord; 
    string filename; 
    ifstream inData; 
    char searchOption; 

    OpenFile(filename, inData); 

    MainMenu(inData, filename); 

    return 0; 
} 

void OpenFile(string& filename, ifstream& inData) 
{ 
    do { 
     cout << "Enter file name to open: "; 
     cin >> filename; 

     inData.open(filename.c_str()); 

     if (!inData) 
      cout << "File not found!" << endl; 

    } while (!inData); 


    if(inData.is_open()) 
    { 

     for(int i=0; i<MAX_RECORDS;i++) 
     { 
      inData >> bookArray[i]; 

     } 
    } 
} 
+4

“entryType”类型没有'operator >>'。 'std :: ifstream'根本不知道如何从文件读入'entryType'。你需要为你的类型重载'operator >>'。看看[这个问题](http://*.com/questions/4421706/operator-overloading)什么运营商重载是如何做到这一点。 –

+0

@FrançoisAndrieux:我有点嫉妒OP。假设你会为对象默认获得一些很好的文件I/O行为。在C++中。 – AndyG

+1

你在哪里告诉计算机如何将一系列字符解释为一个'entryType'?你的C++书籍以什么方式不解释这一点? –

你刚才应该超载operator>>

std::istream& operator>>(std::istream& is, T& object) 
{ 
    // Read object from stream 
    return is; 
} 

其中T将是您创建的类型。

void OpenFile(string& filename, ifstream& inData) 
{ 
    do { 
     cout << "Enter file name to open: "; 
     cin >> filename; 

     inData.open(filename.c_str()); 

     if (!inData) 
      cout << "File not found!" << endl; 

    } while (!inData); 


if(inData.is_open()) 
{ 

    for(int i=0; i<MAX_RECORDS;i++) 
    { 
     inData >> bookArray[i].name.firstName; 

    } 
    } 
}