scanf is resetting the value???

V

vihang

I have a code which is implementing a stack using array..
the code is

[vihang@nine tmp]$ nl pb4.c
1 #include <stdio.h>
2 char stack[100];
3 void push(char i,int top)
4 {
5 stack[top]=i;
6 }
7 void pop(int top)
8 {
9 printf("\n %c",stack[top]);
10 }
11 int main()
12 {
13 int t=0,l;
14 char a,b='y';
15 while(b=='y')
16 {
17 printf("\n\tenter a character\t");
18 scanf("%s",&a);
19 printf("\t1st %d\n",t);
20 push(a,t);
21 t++;
22 printf("\t2nd %d\n",t);
23 if(t>=100)
24 {
25 break;
26 }
27 else
28 {
29 printf("\n do you want to enter another character
y/n\t");
30 scanf("%s",&b);
31 }
32 }
33 l=t-1;
34 while(l>=0)
35 {
36 pop(l);
37 l=l-1;
38 }
39 return(0);
40 }
41

the out put is

[vihang@nine tmp]$ ./a.out

enter a character 1
1st 0
2nd 1

do you want to enter another character y/n y

enter a character 2
1st 0
2nd 1

do you want to enter another character y/n n

if you see the line 21 i am incrementing the value of t,
so if you look at the line 22 it show the incremented value..
but when i try to print it again (line 19) it is showing
non incremented value.

What may be the problem??

thanks in adavance
 
?

=?ISO-8859-1?Q?=22Nils_O=2E_Sel=E5sdal=22?=

vihang said:
I have a code which is implementing a stack using array..
the code is

[vihang@nine tmp]$ nl pb4.c
1 #include <stdio.h>
2 char stack[100];
3 void push(char i,int top)
4 {
5 stack[top]=i;
6 }
7 void pop(int top)
8 {
9 printf("\n %c",stack[top]);
10 }
11 int main()
12 {
13 int t=0,l;
14 char a,b='y';
15 while(b=='y')
16 {
17 printf("\n\tenter a character\t");
18 scanf("%s",&a);
%s stores input as a string. You can't store any interresting string in
a char.
The code here risks overflowing, and Real Bad things here.
Also remember to check the return value of scanf, and expect
illegal user input. Remember to read any \n that a user probably types
as he hits enter.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,460
Latest member
eibafima

Latest Threads

Top