#include <iostream>
using namespace std;
struct list
{
int data;
list *next;
};
list *node, *tail = NULL, *head = NULL;
void add2list();
void extrem();
int main()
{
add2list();
extrem();
return 0;
}
void add2list()
{
int input;
cout << "Adding values to list :\n";
cout << ">>";
while(cin >> input)
{
node = new list;
node->data = input;
node->next = NULL;
if (head == NULL)
{
head = node;
tail = node;
}
else
{
tail->next = node;
tail = node;
}
cout << ">>";
}
}
void extrem()
{
int x, y;
cin >> x >> y;
}
when i run this program it’s only execute the add2list function ????
I’ve added cin.clear(), but the problem is not solved, why??
somecan give clear explaintion about how can I solve this
and When is the use of cin.clear() object useful؟؟
sorry 4 my bad english
There are two reasons why
std::cin >> valuecan fail:std::cinhas reached its end (e.g. by using Ctrl-D or Ctrl-Z, depending on which system you are using)value, i.e., in your case asint. The offending character is, however, not extracted.Obviously, there isn’t anything you can in the first situation: once you have reached the end of the standard input stream there is no way to extend it. So, let’s assume you entered an invalid character, e.g., a letter. Trying to read this letter as an
intwill fail and causestd::ios_base::failbitto be set. Before you can do anything to the stream you need toclear()it. Once you have clearedstd::ios_base::failbityou canignore()the next character and then try again. That is, if you add after your call doadd2list()the following two calls things should be fine, assuming there is only one offending letter (otherwise you might need to ignore more characters):