【发布时间】:2015-05-21 23:52:12
【问题描述】:
我正在处理一个链接列表。它由类组成。当我尝试使用此函数将文本文件中的信息导入列表的第一个指针时:(在底部对我的文件层次结构和代码进行了更详细的描述)
void productList::readInProducts(){
ifstream file;
string line = "";
cout << "What's the name of the file you would like to open?" << endl;
getline(cin, input);//string input is in productList and shared between this function and writeOutProducts()
file.open(input);
if (!file.is_open())
{
cout << "Cannot open " << input << endl;
return;
}
head->products.setName(line);
getline(file, line);
head->products.setPrice(stof(line));
getline(file, line);
head->products.setAmount(stoi(line));
getline(file, line);
while (!file.eof())
{
Node* n = new Node;
n->products.setName(line);
getline(file, line);
n->products.setPrice(stof(line));
getline(file, line);
n->products.setAmount(stoi(line));
getline(file, line);
current = current->next;//make the current pointer point to the next node in the list
current->next = n; //Set the current (empty) node equal to the n which contains three lines from the file
}
}
我收到此错误:
然后visual studio打开(我假设是一个CPP)名为xstring的文件,其中有一个指向第2245行的中断箭头。
现在让我更详细地解释一下我的代码。我有五个文件:productList.h、productList.cpp、product.h、product.cpp 和 main.cpp。这是productList.h:
#include "product.h"
namespace std{
class productList{
public:
productList();
void addAProduct();
void changeInventory();
void printProducts();
void readInProducts();
void writeOutProducts();
private:
short count;
string input; //Used to share the input between the read & write functions
product products[200];
struct Node{
product products;
Node* next;
};
Node* head;
Node* current;
Node* temp;
Node* tail;
};
}
这是product.h:
#include <string>
namespace std{
class product{
public:
product();
string getName();
void setName(string s);
float getPrice();
void setPrice(float p);
int getAmount();
void setAmount(int a);
private:
string name;
float price;
int amount;
};
}
我的 productList.cpp 文件包括:
#include <iostream>
#include <fstream>
#include <iomanip>
#include "productList.h"
我的 product.cpp 文件只包含 product.h,而我的 main.cpp 文件(包含我的执行函数)包含:
#include <iostream>
#include <array>
#include "productList.h"
虽然这些关系看起来有些复杂,但它们都应该是有效的。 cpp 文件以完全相同的名称链接到它们的头文件(假设头文件存在),同时 main.cpp 链接到 productList.h,productList.h 链接到 product.h。我看不出我的代码做错了什么——尽管这可能只是因为我很难这样准确地理解指针是如何工作的。我想错误在我的 productList::readInProducts(){ 函数的代码中,但我不知道出了什么问题。
你们可以提供的任何帮助将不胜感激,因为我很难过。 这是所有文件的保管箱链接: https://www.dropbox.com/s/9welj7k0yy2i1zj/productList.zip?dl=0
【问题讨论】:
-
@RetiredNinja 你错过了
if (!file.is_open())支票吗? -
@Cheersandhth.-Alf 我尝试在
head->products.setName(line);之前添加getline(file, line);。我真的认为这会起作用,或者至少改变我的错误,但我仍然得到完全相同的错误。我已经包含了一个指向包含所有文件(包括 txt 文件)的 zip 文件的链接,以便您可以自己测试这个程序。 -
@RetiredNinja 该文件没有格式错误。
-
@Beta 我在这篇文章的底部添加了一个 Dropbox 链接,它允许您下载包含所有文件(包括文本文件)的 zip 文件,以便您自己测试这个程序.
-
互联网上充斥着损坏的计算机,因为某些程序员认为“我不必测试那种错误情况”。也因为有人想,“当然,我会下载那个匿名 zip 文件。”
标签: c++ class linked-list