SWIFT: Make program wait for input

  • Thread starter Thread starter RoboNerd
  • Start date Start date
  • Tags Tags
    Input Program
Click For Summary
The discussion revolves around a user developing a blackjack game in Swift and encountering an issue with the console input not pausing for user interaction. The user’s code includes a function designed to read input, but it fails to wait for user input, resulting in an immediate return of an empty string. The console output indicates that the program executes the checkpoints without stopping for input. It is suggested that the problem arises from using an interactive playground environment, which may not support the readLine() function properly. The user resolves the issue by switching to a command line tool, where the input function works as intended.
RoboNerd
Messages
410
Reaction score
11
Hi everyone.

I am working on a blackjack game using swift, and I have need to get the user's input from a console. While my code (which is attached below) works in theory, my program does not wait for the user to type some input in the console. Instead, it quickly passes over it and returns an empty string.

If anyone could provide some input that would be great.
My code is shown below:

"""
Code:
func input() -> String
{
    print("Checkpoint 1")
    let input = readLine(stripNewline: true)
    print("Checkpoint 2")
    if (input != nil)
    {
        return input!
    }
    else
    {
        return ""
    }
}

""""

My console output is as following:
"
Curent hand value is: 10. Do you want another card? (yes/no):

Checkpoint 1

Checkpoint 2
"


-----

My program calls the input() function after it asks the user "Do you want another card?" and as one can see by the printing of the checkpoint lines, the console does not stop and wait.

Could anyone please provide some input as to what is going on?

Thanks in advance.
 
Last edited by a moderator:
Technology news on Phys.org
What execution environment? In interactive playground environments or similar you may well find that readLine() always assumes end of file.
 
  • Like
Likes RoboNerd
It is a playground. Thanks for the help!

I shifted to a command line tool and everything works fine now!
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

Replies
1
Views
2K
  • · Replies 14 ·
Replies
14
Views
34K
Replies
55
Views
6K
Replies
17
Views
10K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
3
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K
Replies
1
Views
3K
Replies
2
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K