in reply to getc working twice .

I'm not sure what you mean by its getting executed twice or its hanging up after input but I suspect one of your problems is line termination.

Input from the keyboard is normally buffered. Your program can't ready any input until the user presses the Enter key, after which the whole line of input becomes available to the program, and the input includes the line termination character. Within your program, this will be a single character "\n". For example, if the user presses the key A and waits, the program will do nothing - it won't have any input available to read and getc() will wait. This may not be what you want. If the user then presses the Enter key, the program will have the string "a\n" (assuming the shift or shift lock were not active when A was pressed) available to read. Then getc() will return the next input character: "a". And the next time your program calls getc() it will immediately return the next input character: "\n". This is probably not what you want.

So, you have two issues: line buffering of input and line termination.

What do you want your program to do if the user presses A then B then C then Enter, producing the input "abc\n"?

Maybe you want to process the 'a' and ignore "bc\n". In this case, you could use line oriented input instead of getc(). You might try something like the following:

#! /usr/bin/perl open( FILE, "test.txt" ) || die $!; $mytext = do { local $/; <FILE>; }; $mytext = lc($mytext); $mytext =~ s/[^a-z|]/ /g; @wordarray = split( //, $mytext ); print "@wordarray \n "; $len = @wordarray; print "\n the lenght of the array is : $len "; $i = 0; $j = 0; $iter = 0; while ( $i <= $len - 1 ) { print " \n Value of i is : $i "; print " \n Value of j is : $j "; print " \n Value of character in array is : $wordarray[$i] "; print " \n Enter the character : "; $line = <STDIN>; chomp($line); # remove the trailing line termination if(length($line) > 1) { print "extra characters \"" . substr($line,1) . "\" ignored\n" +; } $char = substr($line,0,1); print " input is $char "; chomp($char); print " \n inputted character is : $char "; if ( $char eq $wordarray[$j] ) { print "Correct !!"; $iter++; $count[$i] = $iter; $j++; $i++; $iter = 0; } else { print "\n Wrong please try again "; $iter++; print "\n Number of attempts : $iter "; } }

Replies are listed 'Best First'.
Re^2: getc working twice .
by jwkrahn (Abbot) on May 29, 2011 at 06:34 UTC

    Please post your code using <code> </code> tags instead of <pre> </pre> tags so it will display properly and be available for download.    TIA