我正在尝试编写一个代码,通过用户获取数字并读取字符'e'或''(空格)也是数字。我的意思是数字'e'或空格'e'数字'e'或空格等等。但我得到荒谬的数字。该程序将显示添加的数字。如果输入'\ n',则停止采取数字(scanf将停止)。 (我很抱歉,因为我对标题一无所知) 我哪里错了。谢谢你们所有赞赏的答案。
示例输入:
#include <stdio.h>
#define MAX 10
void addq ( int *, int, int *, int * ) ;
void test();
int main( )
{
test();
return 0;
}
void test(){
int arr[MAX] ;
int i, front, rear,num ;
char ch;
front = rear = -1 ;
scanf("%c",&ch);
/* initialise data member */
switch(ch){
case 'e':
case ' ':
for ( i = 0 ; i < MAX; i++ ){
arr[i] = scanf("%d",&num);
scanf("%c",&ch);
addq ( arr, num, &front, &rear );
}
break;
}
printf ( "\nElements in the circular queue: " ) ;
display ( arr ) ;
}
void display ( int * arr )
{
int i ;
printf ( "\n" ) ;
for ( i = 0 ; i < MAX ; i++ )
printf ( "%d\t", arr[i] ) ;
printf ( "\n" ) ;
}
/* adds an element to the queue */
void addq ( int *arr, int item, int *pfront, int *prear )
{
if ( ( *prear == MAX - 1 && *pfront == 0 ) || ( *prear + 1 == *pfront ) )
{
printf ( "\nQueue is full." ) ;
return ;
}
if ( *prear == MAX - 1 )
*prear = 0 ;
else
( *prear )++ ;
arr[*prear] = item ;
if ( *pfront == -1 )
*pfront = 0 ;
}
答案 0 :(得分:0)
使用时
scanf("%c",&ch);
它会跳过空格。你应该使用
int ch; // Use type int, not char.
ch = fgetc(stdin);
答案 1 :(得分:0)
#include <stdio.h>
#define MAX 10
typedef struct q {
int arr[MAX];
int front, rear;
} Q;
void init_q(Q *q);
void add_q (Q *q, int v);
void display_q(Q *q);
void test();
int main( ){
test();
return 0;
}
void test(){
int num, end = 0;
char ch;
Q q;
init_q(&q);
scanf("%c", &ch);
while(!end){
switch(ch){
case 'e':
case ' ':
if(1==scanf("%d", &num))
add_q(&q, num);
scanf("%c", &ch);
break;
case '\n':
end = 1;
break;
default:
printf("invalid input(%c)\n", ch);
scanf("%c", &ch);
}
}
printf("\nElements in the circular queue: ") ;
display_q(&q) ;
}
void init_q(Q *q){
q->front = q->rear = -1;
}
int empty_q(Q *q){
return q->front == -1;
}
int full_q(Q *q){
return (q->rear == MAX - 1 && q->front == 0) || q->rear + 1 == q->front;
}
void add_q (Q *q, int item){
if(full_q(q)){
printf( "\nQueue is full.\n");
return ;
}
if( q->rear == MAX - 1 )
q->rear = 0;
else
q->rear++;
q->arr[q->rear] = item;
if(q->front == -1 )
q->front = 0;
}
void display_q(Q *q){
if(!empty_q(q)){
int i = q->front;
printf("\n");
for(;;){
printf("%d\t", q->arr[i]);
if(i++ == q->rear)
break;
if(i == MAX)
i = 0;
}
printf("\n");
}
}