我的程序从用户读取输入并设置目标,然后从用户读取更多输入。然后,它会比较目标初始化后输入的数字和执行次数greater_than,less_than和equal。我很困惑为什么当我输入' ctrl + d'时我的程序不会突破循环。命令不再输入。这是我的期中考试题的代表性例子所以我不允许改变main();或者在list.h中,我并没有违反我的任何教师作弊政策,因为我没有参与这项工作,而是使用了作为学习方法的解决方案。
这是我的代码,提前谢谢。
的main.cpp
#include <iostream>
using namespace std;
#include "list.h"
int main()
{
List list;
int value;
int target;
// first number read is the target
cin >> target;
while (cin >> value)
{
list.insert(value);
}
// initialized to 100 to make sure List::compare() initializes them correctly
int less_than = 100;
int equal = 100;
int greater_than = 100;
list.compare(target, less_than, equal, greater_than);
cout << "target = " << target << endl;
cout << "less_than = " << less_than << endl;
cout << "equal = " << equal << endl;
cout << "greater_than = " << greater_than << endl;
}
list.h
//链接整数列表
#ifndef LIST_H
#define LIST_H
class List
{
public:
List();
~List();
void insert(int value); // insert at beginning of list
void print(); // print all values in the list
void compare(int target, int &less_than, int &equal, int &greater_than);
private:
class Node
{
public:
Node(int value, Node *next)
{m_value = value; m_next = next;}
int m_value;
Node *m_next;
};
Node *m_front;
};
#endif
list.cpp
#include <iostream>
using namespace std;
#include "list.h"
List::List()
{
m_front = NULL;
}
// delete all Nodes in the list
// since they are dynamically allocated using new, they won't go away
// automatically when the list is deleted
// Rule of thumb: destructor deletes all memory created by member functions
List::~List()
{
while (m_front)
{
Node *tmp = m_front;
m_front = m_front->m_next;
delete tmp;
}
}
// always insert at the front of the list
// Note: this works even in the SPECIAL CASE that the list is empty
void List::insert(int value)
{
m_front = new Node(value, m_front);
}
// iterate through all the Nodes in the list and print each Node
void List::print()
{
for (Node *ptr = m_front; ptr; ptr = ptr->m_next)
{
cout << ptr->m_value << endl;
}
}
void List::compare(int target, int &less_than, int &equal, int &greater_than)
{
less_than = 0;
equal = 0;
greater_than = 0;
int targ;
targ = target;
Node *ptr = m_front;
while(ptr != NULL){
if(ptr ->m_value == targ){
equal++;
}
else if (ptr -> m_value > targ){
greater_than++;
}
else if (ptr -> m_value <targ){
less_than++;
}
}
ptr = ptr -> m_next;
}