如何将文本文件字符串存入链表?及Queue::insert(int&)匹配错误排查
解决"no matching function for call to Queue::insert(int&)"错误并实现文本文件行存入链表队列
错误原因分析
你遇到的这个错误本质是类型不匹配:你的Queue类定义的insert方法只接受string类型的参数,但在main函数的for循环里,你传入的是int类型的变量i(Q.insert(i))。C++是强类型语言,编译器找不到接受int参数的insert重载函数,所以抛出了这个错误。而且这段for循环的逻辑和你实际需求(读取文本文件行存入队列)完全无关,需要替换成正确的文件读取逻辑。
修正后的完整代码
我已经帮你调整了代码,实现了读取文本文件每一行存入队列的功能,同时修复了错误:
#include<iostream> #include<fstream> #include<string> using namespace std; struct Node{ string data; Node *next; }; class Queue{ public: Node *front,*rear; Queue(){front=rear=NULL;} void insert(string n); void deleteitem(); void display(); ~Queue(); }; void Queue::insert(string n){ Node *temp=new Node; if(temp==NULL){ cout<<"Overflow"<<endl; return; } temp->data=n; temp->next=NULL; //for first node if(front==NULL){ front=rear=temp; } else{ rear->next=temp; rear=temp; } cout<<n<<" has been inserted successfully."<<endl; } void Queue::display(){ if(front==NULL){ cout<<"Underflow."<<endl; return; } Node *temp=front; //will check until NULL is not found while(temp){ cout<<temp->data<<" "; temp=temp->next; } cout<<endl; } void Queue :: deleteitem() { if (front==NULL){ cout<<"underflow"<<endl; return; } cout<<front->data<<" is being deleted "<<endl; if(front==rear)//if only one node is there front=rear=NULL; else front=front->next; } Queue ::~Queue() { while(front!=NULL) { Node *temp=front; front=front->next; delete temp; } rear=NULL; } int main(){ ifstream file; file.open("exp.txt"); // 先检查文件是否成功打开 if (!file.is_open()) { cout << "无法打开文件exp.txt" << endl; return 1; } Queue Q; Q.display(); // 初始为空,会输出Underflow string line; // 循环读取文件的每一行,直到文件结束 while (getline(file, line)) { Q.insert(line); } Q.display(); // 显示队列中的所有行 // 循环删除直到队列为空 while (Q.front != NULL) { Q.deleteitem(); } file.close(); // 关闭文件 return 0; }
关键修改点说明
- 移除错误的int插入逻辑:删掉了原来的
for(int i = 0; i<5; i++) { Q.insert(i); },因为这和你的需求无关,还导致了类型错误。 - 添加文件打开检查:增加了
if (!file.is_open())的判断,避免文件不存在或无法打开时程序崩溃。 - 实现按行读取文件:使用
getline(file, line)循环读取文件的每一行,把每行字符串传入Q.insert,完美匹配你的需求。 - 优化删除逻辑:改成循环删除直到队列为空,逻辑更合理。
测试说明
确保你的exp.txt文件和程序在同一目录下,无论文件内容是单行还是多行,程序都会正确读取每一行并插入队列,之后显示所有内容再逐个删除。
内容的提问来源于stack exchange,提问作者Funmi Orekoya
相关产品推荐
相关产品推荐

