Good afternoon! How are you all holding up today? I "accidentally" ate piece of cake at the cafe I'm currectly sitting in, even though I had promised myself not to eat sugar until next week. Fail. 😅
Don't mind the English language, since this is an excerpt from a larger piece of code.
If I enter anything other than 'Y' and 'N' using a single character, the code works as I want it to, but, naturally, if I enter anything other than 'Y' and 'N' multiple times, the if is executed the same amount of times as characters entered, which is ugly. Trying to limit this with %1c also doesn't work, since I suppose that only works with strings? Is this a limitation of scanf or rather how the logic is implemented?
Feel free to NOT provide the correct answer right away, but instead, give me the topic or the function to read up on. 😊
char letter = '\0';
while(1) {
printf("nter the letter 'Y' or 'N': ");
scanf(" %c", &letter);
if (letter != 'Y' && letter != 'N') { //"broken" because multicharacter input executes this condition that many times.
printf("You have to enter 'Y' or 'N'! You have entered %c!\nE", letter);
}
else { break; }
}
printf("Good job! You have entered: %c.\n", letter);
8 Comments
lemmysmash@piefed.social · 6 pts · 85d
I'm too lazy to confirm, but I think scanf (as well as many other I/O functions) works on top of the buffered input. I.e. when you scanned only one character on the first run of scanf but there are more left in the buffer, then subsequent calls will read from that buffer, e.g.
In general you have two options:
For both cases, do your research on how to do it :) That K&R from above should be a great start indeed.
akunohana@piefed.blahaj.zone · 3 pts · 85d
Thanks very much! I had no idea there is such a thing as "unbuffered I/O". I'll look into it. :)
hkwln@lemmy.ml · 3 pts · 83d
you could also use getchar() to only take the first char out of the buffer, if you didn't know already ;)
akunohana@piefed.blahaj.zone · 2 pts · 83d
I'll try this soon. 😊 To my defense, I don't have a bathtub in which I could arrive at these kinds of ideas 🤣
kiri@ani.social · 3 pts · 85d
read #1.5 and #7: K&R
or just find examples of
getchar()orfgets()akunohana@piefed.blahaj.zone · 2 pts · 85d
Thanks! I'll look 'em up! :)
iusemybrain@sh.itjust.works · 1 pts · 52d
I would do the loop instead the if condition, where letter != 'Y' or 'N' generally speaking, using while(1) for x86_64 programming is bad practice, specific cases like embedded system design is where it's more commonly used.
ExperimentalGuy@programming.dev · 1 pts · 83d
Use gets on a stack buffer, but don't enable stack canaries and make the stack both writable and executable. Your users will thank you.