Не считывается символ char
#include <stdio.h>
#include <stdlib.h>
#define MAX_WORD 10
struct Component{
enum {isInt, isChar, isString} type;
int num;
char symbol;
char string[MAX_WORD];
void* val;
};
void push(struct Component *c){
printf("which type will be pushed?\n1 - int\n2 - char\n3 - string\n");
int temp;
scanf("%d", &temp);
switch(temp){
case 1:
c->type = isInt;
int intValue;
printf("Enter number\t");
scanf("%d", &intValue);
c->num = intValue;
break;
case 2:
c->type = isChar;
char charValue;
printf("Enter char\t");
scanf("%c", &charValue);
c->symbol = charValue;
break;
case 3:
c->type = isString;
break;
}
}
int main()
{
int count; // Сколько элементов будет в множестве?
scanf("%d", &count);
struct Component comp[count];
for(int i = 0; i < count; i++){
struct Component *ptr = &comp[i];
push(ptr);
}
return 0;
}
когда вызываю функцию scanf() для символа scanf("%c", &charValue);, программа просто пропускает ввод символа, хотя с scanf("%d", &intValue); такой проблемы нет.
Подскажите, что не так делаю?
Ответы (1 шт):
Автор решения: avp
→ Ссылка
Вообще-то, все описано в man scanf
c Matches a sequence of characters whose length is specified by the maximum field width (default 1); the next pointer must be a pointer to char, and there must be enough room for all the characters (no terminating null byte is added). The usual skip of leading white space is suppressed. To skip white space first, use an explicit space in the format.
Обратите внимание -- The usual skip of leading white space is suppressed -- т.е. в вашем случае, например, после ввода числа scanf("%c", ...); прочтет символ \n, который завершал цепочку цифр.
Тут же написано, что для исправления ситуации -- use an explicit space in the format.
Т.о. напишите формат с пробелом перед %c -- scanf(" %c", &charValue); -- и будет вам счастье.