目标是将Nim在Haskell中的游戏编码为学校作业.我是Haskell的新手,在尝试读取输入时会出现奇怪的行为.
目标是读取两个整数.而不是打印第一个消息,然后提示然后继续第二个消息,它只打印两个消息,我无法给出正确的输入.这有什么不对?
type Board = [Int] -- The board
type Heap = Int -- id of heap
type Turn = (Int, Int) -- heap and number of stars to remove
readInt :: String -> IO Int
readInt msg = do putStr (msg ++ "> ")
inp <- getChar
let x = ord inp
return x
readTurn :: Board -> IO(Turn)
readTurn b = do heap <- readInt "Select heap:"
amt <- readInt "Select stars:"
print heap
print amt
return(heap, amt)
Run Code Online (Sandbox Code Playgroud)
问题是stdout默认情况下是行缓冲,这意味着在打印换行符之前不会输出任何内容.有两种方法可以解决这个问题:
hFlush stdout打印提示后使用以刷新缓冲区.hSetBuffering stdout NoBuffering在程序开始时使用以禁用输出缓冲.此外,使用getChar和ord将读取单个字符并为您提供其ASCII值,这可能不是您想要的.要读取和解析数字,请使用readLn:
import System.IO (hFlush, stdout)
readInt :: String -> IO Int
readInt msg = do
putStr (msg ++ "> ")
hFlush stdout
readLn
Run Code Online (Sandbox Code Playgroud)