#include
int main() {
struct cerchio c1, c2;
float distanza;
char k;
//input del centro del primo cerchio
printf(\"Enter the co
scanf("%s", &k);
should be
scanf(" %c", &k);
%c
is the right format specifier for a character(char
) while %s
is used for strings. The space character behind %c
skips all whitespace characters including none, until the first non-whitespace character as specified in the C11 standard:
7.21.6.2 The fscanf function
[...]
- A directive composed of white-space character(s) is executed by reading input up to the first non-white-space character (which remains unread), or until no more characters can be read. The directive never fails
The reason why your program wouldn't wait for further input when you used %c
is because there was a newline character(\n
) prevailing in the standard input stream(stdin
). Remembering pressing enter after entering data for each scanf
? The newline character is not captured by the scanf
with %f
. This character is instead captured by the scanf
with %c
. This is why this scanf
doesn't wait for further input.
As for why your other scanf
s(with a %f
) did not consume \n
is because the %f
skips whitespace characters as seen in the C11 standard:
7.21.6.2 The fscanf function
[...]
- Input white-space characters (as specified by the
isspace
function) are skipped, unless the specification includes a[
,c
, orn
specifier. 284
As for why your program worked when you used is because you were lucky. Using %s
instead of %c
invokes Undefined Behavior. This is because %s
matches a sequence of non-whitespace characters and adds a NUL-terminator at the end. Once a user enters anything, the first character is stored in k
while the rest of the characters(if any) as well as the \0
is written in an invalid memory location.
If you are currently thinking why the %s
format specifier did not consume the \n
is because it skips whitespace characters.
use
scanf(" %c",&k);
Instead of
scanf("%s", &k); // %s is used for strings, Use %c for character variable.
for char variable use " %c". and don't forget to keep space before %c " %c"
, it will skips newline and whitespace characters.