我是一名haskell初學者。我的代碼:無法同時接受2個輸入
module Main (main) where
import System.IO
--Type for identifying Students.
data Student = Student {
name :: String,
regnum :: Integer
} deriving (Show, Read)
getData :: IO (String)
getData = do
putStr "\tEnter the student's name: "
name <- getLine
putStr "\tEnter the registration number: "
regstr <- getLine
let regno = (read regstr) :: Integer
return (show (Student name regno))
addData :: String -> IO (Bool)
addData filename = do
fileData <- getData
appendFile filename fileData
return True
printData :: String -> IO (Bool)
printData filename = do
fileData <- readFile filename
putStrLn fileData
return True
resetFile :: String -> IO (Bool)
resetFile filename = writeFile filename "" >> return True
action :: Char -> String -> IO (Bool)
action option filename =
if option == '1'
then addData filename
else if option == '2'
then printData filename
else if option == '3'
then resetFile filename
else return False
main = do
putStr "What do you want to do?\n\t1) Add a new record to a file.\n\t2) Read a record from a file.\n\t3) Reset the file.\n>> "
option <- getChar
action option "records.txt"
我得到的輸出是:
What do you want to do?
1) Add a new record to a file.
2) Read a record from a file.
3) Reset the file.
>> 1
Enter the student's name: Enter the registration number:
因此我無法提供輸入,爲學生的姓名。我正在運行ghci上的代碼。當我試圖看到它如何作爲可執行文件運行時,它會輸出一個更奇怪的結果。
What do you want to do?
1) Add a new record to a file.
2) Read a record from a file.
3) Reset the file.
(注意它不打印「>>」)。只有在我按兩次Enter鍵後纔會打印「>>」。 我不明白這裏發生了什麼。我的代碼的其他改進非常受歡迎。
編輯::使用函數getline代替的getchar,該項目工程ghci中(感謝丹尼爾·菲捨爾)。但編譯時仍然不起作用。新的輸出是:
What do you want to do?
1) Add a new record to a file.
2) Read a record from a file.
3) Reset the file.
1 (Typed my me)
Tom (Typed my me)
234 (Typed my me)
>> Enter the student's name: Enter the registration number:
在重新運行來讀取文件:
What do you want to do?
1) Add a new record to a file.
2) Read a record from a file.
3) Reset the file.
2 (Typed my me)
>> Student {name = "Tom", regnum = 234}
爲什麼是「>>」,並採取了輸入後正在打印的getData的putStr
S'
你使用的是Windows嗎? – 2012-07-14 13:19:56
@ n.m。是。我在窗戶上。 – Likhit 2012-07-14 13:20:46
不要使用'getChar'獲取交互式輸入,它不會按預期工作。 'hSetBuffering stdin NoBuffering'可能會或可能不會幫助到這裏,因爲終端可能會做自己的行緩衝。 – 2012-07-14 13:36:51