![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
|
c stack implementation
hey..my question is not really related to the stack itslef but to something ive encountered while i was writing the code for it:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define SIZE 5
void push(int);
int pop(void);
void printstack(void);
int stack[SIZE], *top = &stack[49], *current, input;
int c;
int main()
{
current = stack;
do {
printf("Enter the integer: ");
scanf("%d", &input);
push(input);
printf("Do you want to continue (1 for yes / 2 for no): ");
scanf("%d", &c);
}while(c == 1);
printstack();
}
void push(int i)
{
if(current <= top)
{
*current = i;
current++;
}
else
{
printf("Stack Overflow occured\nPrinting started: ");
printstack();
}
}
int pop()
{
current--;
int temp = *current;
return temp;
}
void printstack()
{
while(current != stack)
printf("%d ", pop());
printf("\n");
}#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define SIZE 5
void push(int);
int pop(void);
void printstack(void);
int stack[SIZE], *top = &stack[49], *current, input;
char c;
int main()
{
current = stack;
do {
printf("Enter the integer: ");
scanf("%d", &input);
push(input);
printf("Do you want to continue (y/n): ");
scanf("%c", &c);
}while(c == 'y');
printstack();
}
void push(int i)
{
if(current <= top)
{
*current = i;
current++;
}
else
{
printf("Stack Overflow occured\nPrinting started: ");
printstack();
}
}
int pop()
{
current--;
int temp = *current;
return temp;
}
void printstack()
{
while(current != stack)
printf("%d ", pop());
printf("\n");
} |
|
|
|
|
|
#2 |
|
Expert Programmer
Join Date: Jun 2005
Posts: 893
Rep Power: 4
![]() |
The problem is that first scanf is only reading the number you have typed in, and is not reading the carriage return that you also typed to enter the data. When the second scanf is run looking for any character, that character is the carriage return.
There are lots of threads in the forum where this is discussed, along with options for fixing it. |
|
|
|
|
|
#3 | |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
I wrote this three or four years ago. Stay tuned for it to appear someplace permanent. I'll work in the slightly different "unexpected (but correct) content" phenomenon mentioned by The Dark.
Quote:
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|