I am new to Haskell, kinda 2 days since I study Haskell, and I want to do a project with files. I did it already in c++ and now I want to do it in Haskell too. A little part of project is about a library, where I can register a book and a person. Now I want to put book code into a file.txt but to store it as int, not as String, because I have to search and compare this code , with other codes later, and will be easier to compare. Here is my code, and I receive the following error *** Exception: Prelude.read: no parse. Does anyone know how to solve this please?
import System.IO
main = do
putStrLn "Please put book details"
putStr "Code: "
code <- getLine
let code1 = read code
appendFile "book.txt" ("Cod:" ++ code1 ++ "\n")
This fails since you're attempting to read a String as a String.
read is used to parse a String as an object. To parse a String as a String though, you need to add explicit quotes around the String being parsed. Failing to do so will result in the error that you got. You can test this by adding "s around the input when your program asks for it. It should work.
Do you expect code1 to be an int? If that's the case, there's 2 problems (and a couple ways to solve them) :
You need to tell read what type you want it to parse the string as. To do that, use a type annotation. Add :: int after read code.
Since you can't concatenate an int, change code1 in your last line to (show code1) to convert it back to a String.
The problem with the above way is you're converting from, then to a String. You could avoid any converting by keeping it as a String by skipping the read altogether:
import System.IO
main = do
putStrLn "Please put book details"
putStr "Code: "
code <- getLine
# Check user's input to ensure it's correct.
appendFile "book.txt" ("Cod:" ++ code)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With