Re: [Dev-C++] Simplification for my code please
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <or...@vp...> - 2003-10-19 14:19:54
|
Coosa wrote:
> I had today a lab test in C++ and one of the 10 questions was to write a
> program which accepts a string input and reverse the words separately
> between spaces and outputs it to the stream. I couldn’t solve it in time
> and I lost the marks for this section and went home and solved it.
I GUESS this exercise could be a typical use of stack and stack
operations: push, pop.
First, have a stack implemented, which can handle arbitrary size, also
implement push and pop. The rest of the task is simple:
(draft)
ch = read character;
if (ch == space){
write each stack character using pop();
write whitespace;
}
else{
push(ch);
}
Make a loop of the above and that's all.
Of course, if you need to take care of new lines and tabs too, then you
can extend the first "if" statement, like:
if (ch == space || ch == tab || ch == newline, ...)
Working implementations attached:
- reverse.c
It can work with any word-length.
- reverse_simple.c
This is more compact, however max word length is hard coded.
Both read from stdin and write to stdout (redirect if you need). They
read until EOF is read. Both are simple C programs, no C++ here. The
stack implementation is primitive, no checking performed, however there
should be no problem of that, due to the known use of the stack.
Hope they help.
--
Greetings,
Balázs
|