2

Im comming from C++.

This code:

 int main() {
     int age; 
     std::cout << "Type your age: ";
     std::cin  >> age;
     return 0;
 }

Would produce something like this on terminal:

 Type your age: _

I can enter the age value on the same line of the message.

How can I achieve the same result in Haskell?

Augusto Dias
  • 147
  • 1
  • 10
  • 2
    What Haskell code did you try? – 4castle Dec 11 '18 at 05:46
  • Possible duplicate of [IO happens out of order when using getLine and putStr](https://stackoverflow.com/questions/13190314/io-happens-out-of-order-when-using-getline-and-putstr) – AJF Dec 11 '18 at 07:18
  • 4
    I would not turn off buffering, as the answers below propose, but instead run `hFlush stdout` after the message is printed, to be sure all the buffers are pushed to the screen. – chi Dec 11 '18 at 08:44

2 Answers2

5

You can use putStr function to print message without newline at the end as:

import System.IO

main = do hSetBuffering stdout NoBuffering
          putStr "Type your age: "
          age <- readLn::IO Int
          return ()
assembly.jc
  • 2,056
  • 1
  • 7
  • 16
3

By default output is written to a buffer until there's a newline and only then actually written to stdout. To disable the buffer and just write directly to stdout you want to run hSetBuffering stdout NoBuffering. (The relevant bindings are found in System.IO)

soupi
  • 1,013
  • 6
  • 6