Question

Let's say that the user input = 6000 and the number inside input.txt is = 5000. The sum up will be 11000. The number that will be displayed on the screen and the value stored in the file will be overwritten to 11000. Please help me, Thanks

import System.IO

menu :: IO ()
menu = do

handle <- openFile "input.txt" ReadMode  
          contents <- hGetContents handle 
      putStr contents
      hClose handle
      contents <- readFile "input.txt"
      print . sum . read $ contents
      putStr("\nThe amount of money that you want to deposit : ")
      y<-getLine
Was it helpful?

Solution

Whats wrong with yor code :

Lots of problems with your code.

  • Why are you reading two times.
  • Why there is a getLine at the end.
  • The types of most of the functions you have used do not match.
  • Does the input file contains only one line or many lines.

It is better to see types of functions you are using and then compose them.

A probable correction of your code from what I can infer you want would be

import System.IO

main :: IO ()
main = do
    y<-getLine
    content <- readFile "input.txt"
    let out = sum $ map read $ y:(words content)
    putStrLn $ "\nThe amount of money that you want to deposit : " ++ show out
    writeFile "input.txt" $ show out

Direct answer :

It is better to use withFile as you want to read and then write. readFile reads the file lazily so there is no guarantee when the file handle will be closed. In the above case if you write the writeFile line before printing the output it might give a runtime error complaining about open handles. So withFile is a safer option and you will be opening file only once as compared to twice in the above case.

I have considered that you just want to add the number in the first line of the input file with the number you input.

import System.IO

main = do
    input <- getLine
    out <- sumFile (read input) "input.txt"
    putStr $ "\nThe amount of money that you want to deposit : " ++ show out

sumFile :: Int -> FilePath -> IO Int
sumFile input fp = withFile fp ReadWriteMode add
    where
        add handle = do
            number <- hGetLine handle
            hSeek handle AbsoluteSeek 0
            let sum = input + read number
            hPutStrLn handle (show sum)
            return sum
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top