SixTwentyFour
SixTwentyFour

Reputation: 41

Why does this c-shell script stop?

The script is supposed to print "Enter the nest number to add: " and keep doing this until the user enters a negative number. At which point it is supposed to print the sum of the positive numbers. However as is the loop asks for the next number one time, it is entered, and then does not ask again, the script just stops doing anything and doesn't even reach the next line within the loop.

#!/bin/csh -x
#
# This script adds positive numbers entered by the user, stopping
# when a negative number is added
# Usage: +#, +#, +#... -#. 
#
@ x=0
@ sum = 0
while($x>= 0)
echo -n  "Enter the next number to be added: "
@ sum = $sum + $<
@ x = $<
end
#
exit 0

Upvotes: 1

Views: 120

Answers (1)

suspectus
suspectus

Reputation: 17258

$< reads a line from stdin. This must be assigned to a variable, else if $< is used a second time the script will expect further input before continuing.

@ x=0
@ sum = 0
while ($x >= 0)
   echo -n  "Enter the next number to be added: "
   @ x = $<
   if ($x >= 0) then
      @ sum = $sum + $x
   endif
end
echo $sum
exit 0

Upvotes: 1

Related Questions