Why doesn't this piece of code work?

kdevel kdevel at vogtner.de
Mon May 16 22:25:23 UTC 2022


On Monday, 16 May 2022 at 16:53:15 UTC, SvGaming wrote:
[...]
> https://github.com/svgaming234/ezusb
> forgot to post it in the previous reply, I am kind of stupid

In main your program reads an integer:

```
    int n;
    writef("Pick an option: ");
    readf(" %s", &n);
```

but your console/Terminal is line buffered, i.e. you type 1 plus 
a newline ("\n"). Only after the newline the OS transfers control 
back to your program. Unfortunately your program does not consume 
the newline, as ltrace reveals the newline is put back to the 
input buffer with ungetch. Therefore the next read command

```
    string a;
    a = readln();
    writeln(a);
```

consumes that newline from your first input resulting in variable 
a containing the empty string ending with a newline. Following 
change fixes the issue:

```
    int n;
    writef("Pick an option: ");
    readf(" %s\n", &n); // explicitly read the newline
```

I am not sure, why %s fits here. I would have expected a %d 
format for parsing the integer.



More information about the Digitalmars-d-learn mailing list