scanf not working well in C
165 просмотра
4 ответа
if (a % 5)
goto ask;
else
goto main;
ask:printf("Do You Want To Exit ? Y \\ N . . . \n");
scanf("%c", &YN);
getch();
if (YN == 'Y')
{
y: system("cls");
YN = 1;
goto sign;
}
else if (YN == 'y')
goto y;
else if (YN == 'N')
{
n: system("cls");
YN = 0;
goto sign;
}
else if (YN == 'n')
{
goto n;
}
else
{
printf("Sorry ..Didn't Catch that ... ");
goto ask;
}
someone help me understand my problem for somereason the output I get from this code is "Do u want to exit y\n ?" getchar ... "sorry didnt catch that do u want to exit y\n ? "
It looks like it jumped over the scanf()
for the first time and the program went directly to the else
==> "sorry i didnt get that"
and only in the second time it fiugres out how to use the scanf()
.
Ответы (4)
1 плюс
scanf()
reads characters with %c
and yes, the ENTER key press [after your previous input] is pretty much vaild for %c
[Check the below spoiler].
ENTER key press == newline
use
scanf(" %c", &YN); //mind the space brefore `%c`
^
|
to ignore any previously-stored [also, leading] whitespace [including a newline.]
Note: This also eliminates the need for your getch();
1 плюс
When scanf
reads anything, it leaves the newline added by the Enter in the input buffer. The "%c"
format reads any character in the input buffer, including newlines. So the first call will read and extract one character from the input buffer, but the next call will read the newline character left over from the previous call.
Adding a leading space to the format string tells scanf
to read (and ignore) any whitespace (space, tab, newlines) before it tries to parse and extract your format.
I recommend you read e.g. this scanf
reference for more information.
0 плюса
0 плюса
Add a space before %c
to skip the newline character from the stdin
which you had pressed after entering data for the scanf
for the first time. This happens because scanf
does not consume the \n
character(Enter key) which you press after you enter any character .As the Enter key(\n
) is also a character,it gets consumed by the scanf
the second time and hence does not wait for further input.
Also,using goto
s is usually bad practice. See this for more info about this.
Вопросы из категории :
- c Как вы форматируете unsigned long long int, используя printf?
- c What are the barriers to understanding pointers and what can be done to overcome them?
- c Как реализовать продолжения?
- c Как вы передаете функцию в качестве параметра в C?
- c Как получить список каталогов в C?
- c В чем разница между #include <filename> и #include "filename"?
- c Всегда ли выгодно использовать «goto» в языке, который поддерживает циклы и функции? Если так, то почему?
- c В чем разница между ++ i и i ++?
- c Есть ли разница в производительности между i ++ и ++ i в C?
- c Какой самый лучший бесплатный детектор утечки памяти для программы на C / C ++ и ее подключаемых библиотек DLL?
- scanf Разбор ввода с помощью scanf в C
- scanf Ищете C # эквивалент Scanf
- scanf Как вы можете вводить пробелы с помощью scanf?
- scanf Scanf пропускает все остальные циклы while в C
- scanf Почему scanf () вызывает бесконечный цикл в этом коде?
- scanf Принимает ли scanf () '\ n' в качестве остатка ввода от предыдущего scanf ()?
- scanf В чем разница между спецификаторами преобразования% i и% d в отформатированных функциях ввода-вывода (* printf / * scanf)
- scanf C - пытается прочитать один символ из стандартного ввода (и не удается) w / scanf / getchar
- scanf Использование препроцессора C для создания строкового литерала для scanf?
- scanf Как пропустить строку при сканировании текстового файла?