0

我想这曾经发生在我身上。这是A3.txt

%INSERT
MARK 29 
DAVID 21
JOHN 44
JOHN 51
LARRY 39
MARK 21
DAVID 18
JOHN 28
MARK 35
DONALD 41
PHIL 26

即使我sourcefile >> reader在循环结束时使用,程序仍在输出"reader: MARK",这意味着该sourcefile >> reader;语句不起作用(即,它一遍又一遍地获得相同的输入,或者它没有获得任何输入)。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;  

struct data
{
 string name;
 int id;
 data* link;
};

data* start;
data* node;
ifstream sourcefile;

int main()
{
 data* start = new data;

 start -> link = NULL;

 string input;
 string reader;
 sourcefile.open("A3.txt");

 bool firstnode = true;

 sourcefile >> input;

 node = start;

 cout << "Recieved command: " << input << endl;

 if(input == "%INSERT")
 {
  // unlike the other ones, this function keeps reading until it hits another command
  sourcefile >> reader;

  cout << "Insert name: " << reader << endl;


  // iterates through the link list until it hits the final node
  while(node -> link != NULL)
    node = node -> link;


  while(reader[0] != '%')
  {
   if(firstnode)
    start -> link = new data;
   else
    node -> link = new data;


   sourcefile >> node -> name;
   sourcefile >> node -> id;
   node -> link = NULL;

   sourcefile >> reader;
   cout << "reader: " << reader << endl;
  }
 }
 else
  return 0;

}

还有……题外话。编译器说switch语句不能与字符串一起使用,这是真的,还是我做错了什么?

4

2 回答 2

2

sourcefile >> node -> id;失败,之后没有任何输入操作sourcefile成功,正如在流中failbit设置的那样。失败,因为它尝试读取整数但在流中遇到“DAVID”。发生这种情况是因为消耗“MARK”,消耗“29”,然后留下“DAVID”。尝试替换为.sourcefilesourcefile >> node -> id;sourcefile >> reader;sourcefile >> node -> name;sourcefile >> node -> id;sourcefile >> node -> name;node -> name = reader

是的,您不能在 中使用字符串switch,只能使用整数和枚举表达式。

在另一个题外话中,您似乎没有释放为节点分配的内存(简单的解决方案:只需使用std::list)。

编辑:这是您的程序在使用时的样子std::list

#include <iostream>
#include <fstream>
#include <string>
#include <list>

using namespace std;  

struct data
{
 string name;
 int id;
};

ifstream sourcefile;

int main()
{
 list< data > datalist;

 string input;
 string reader;
 sourcefile.open("A3.txt");

 sourcefile >> input;

 cout << "Received command: " << input << endl;

 if(input == "%INSERT")
 {
  // unlike the other ones, this function keeps reading until it hits another command
  sourcefile >> reader;

  cout << "Insert name: " << reader << endl;

  while(reader[0] != '%')
  {
   data d;
   d.name = reader;
   sourcefile >> d.id;
   datalist.push_back( d );

   sourcefile >> reader;
   cout << "reader: " << reader << endl;
  }
 }
}
于 2010-10-15T19:45:40.177 回答
2

现在你的代码做的太多了。程序解决一系列子问题,试图解决更大的问题。这就引出了单一职责原则

这意味着一个对象(类、函数等)应该解决一个问题。但现在这还没有发生。例如,main琐碎地做不止一件事:它管理列表的节点(也不正确!没有任何内容被删除!),并从用户那里获取输入。这太多了。

相反,把事情分开。您应该创建一个list管理节点的类,然后main应该使用它。请注意这里的区别:main不再解决该问题,它利用了可以解决的问题。

因此,考虑到这一点,它很快就会跟随我们拆分的越多,就越容易纠正、修复和维护。获取代码并将其拆分的行为是“重构”。让我们这样做。

首先,我们需要一个链表来使用。通常我们有std::vector(注意:链表通常是最糟糕的容器)或std::list但由于你的老师被误导了,他让你自己写。您的任务应该是编写一个列表容器或使用一个列表容器并读取输入,而不是两者兼而有之。(同样,在现实世界中,我们将事物分开;为什么要教人们混合它们?)

您已经掌握了基础知识,只需要对其进行封装。(如果你还不知道课程,让我知道,我也会在那里扩展;当我们在做的时候,如果你还不知道,你可能想要一本好书来自学你的老师是什么' t):

// normally this should be a template so it can store anything,
// and yadda yadda (more features), but let's just make it basic
// this data class is what the linked list holds
struct data
{
    std::string name;
    int id;
};

class linked_list
{
public:
    linked_list() :
    mHead(0)
    {}

    // the magic: the destructor will always run 
    // on objects that aren't dynamically allocated,
    // so we're guaranteed our resources will be
    // released properly
    ~linked_list()
    {
        // walk through the list, free each node
        while (mHead)
        {
            node* toDelete = mHead; // store current head
            mHead = mHead->next; // move to next node

            delete toDelete; // delete old head
        }
    }

    void push_back(const data& pData)
    {
        // allocate the new node
        node* newNode = new node(pData, mHead); 

        // insert
        mHead = newNode;
    }

    data pop_back()
    {
        // remove
        node* oldNode = mHead;
        mHead = mHead->next;

        // deallocate
        data d = oldNode->data;
        delete oldNode;
        return d;

        /*
        the above is *not* safe. if copying the data throws
        an exception, we will leak the node. better would be
        to use auto_ptr like this:

        // now the node will be deleted when the function ends, always
        std::auto_ptr<node> n(oldNode);

        // copy and return, or copy and throw; either way is safe
        return n->data;

        but who knows if your <strike>dumb</strike>misguided
        would allow it. so for now, make it unsafe. i doubt
        he'd notice anyway.
        */
    }

private:
    // any class that manages memory (i.e., has a destructor) also needs to
    // properly handle copying and assignment.
    // this is known as The Rule of Three; for now we just make the class
    // noncopyable, so we don't deal with those issues.
    linked_list(const linked_list&); // private and not defined means it
    linked_list& operator=(const linked_list&); // cannot be copied or assigned

    struct node
    {
        // for convenience, give it a constructor
        node(const data& pData, node* pNext) :
        d(pData),
        next(pNext)
        {}

        data d; // data we store
        node* next; // and the next node
    };

    node* mHead; // head of list
};

现在你有一个可以使用的列表。main将不再为这些事情烦恼:

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>

using namespace std; // should generally be avoided

// your linked_list code

int main()
{
    // don't declare variables until you need them,
    // and avoid globals. (the previous rule helps)
    ifstream sourcefile("A3.txt");

    // check that it opened
    if (!sourceFile.is_open())
    {
        cerr << "could not open file" << endl;

        // EXIT_FAILURE is inside <cstdlib>
        return EXIT_FAILURE;
    }

    string input;
    sourcefile >> input;

    cout << "Received command: " << input << endl;

    linked_list datalist;
    if (input == "%INSERT")
    {
        string reader;
        sourcefile >> reader;

        cout << "Insert name: " << reader << endl;

        while (reader[0] != '%')
        {
            data d;
            d.name = reader;
            sourcefile >> d.id;

            datalist.push_back(d);

            sourcefile >> reader;
            cout << "reader: " << reader << endl;
        }
    }
}

注意它是多么容易阅读。您不再管理列表,而只是使用它。并且列表会自行管理,因此您永远不会泄漏任何内容。

这是您要采取的方法:将事物包装成能够正确解决一个问题的工作对象,然后将它们一起使用。

于 2010-10-15T20:49:12.443 回答