size of input.

hi, im trying to overload the >> to take in some numbers separated by space and insert pairs of them in nodes in a linked list,the thing is I want it to take in eg. " 1_34_ 56_6 " hence run the while loop twice.but, how do i set up the loop termination condition?? is there any other way to do it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
istream &operator>>( istream &input, List &list )
{
   int temp_x;
   int temp_y;

   while(..........)
   {
   input >> temp_x;
   input >> temp_y;
   list.InsertNode(temp_x,temp_y);
   }

   return input;
}
Last edited on
What terminates the input? Newline? End-of-file? Invalid character?

For example, this would continue to read pairs until an invalid character was reached:

1
2
3
4
5
6
7
8
9
10
11
istream& operator>>( istream& is, List& list ) 
{
    while( is ) {
         int x, y;
         is >> x >> y;
         if( is ) 
             list.InsertNode( x, y );
    }

    return is;
}


So the loop will terminate on EOF, newline, or a character is read that cannot be interpreted as an int. (But whitespace is fine).


You need to decide what terminates a list (as it is written). For example, you can write a list of numbers as:
1 2 7 -3 98 5
...in which case the list ends when the input ends.

You could write a list as:
(1 2 7 -3 98 5)
which makes it easier to 1. recognize a list (it starts with an open parenthesis) and 2. recognize the end of the list (it ends with a close parenthesis).

You could embed information about the list:
#list 6 1 2 7 -3 98 5
which again makes it easy to recognize a list, tells information about the list (it has 6 elements), and gives the list following.


Effectively, how you _write_ the list matters a great deal. I personally like s-expressions:
((1 2) (7 -3) (98 5))
this would make it very easy to parse lists of lists... or a list of pairs, etc.


Last thing. You should abort if there is an input error:
1
2
3
4
5
6
  while (...)
  {
  if (!(input >> temp_x)) break;
  if (!(input >> temp_y)) break;
  list.InsertNode( temp_x, temp_y );
  }

That way improper lists and prematurely-terminated lists won't cause extraneous (and invalid) input to get tacked-on to the end of your list.

Hope this helps.

[edit] jsmith: a newline is whitespace...
Last edited on
yes i want it to stop when the input ends, but how do i know when the input will end? ie, what condition will i set?
Last edited on
Topic archived. No new replies allowed.