Re: [Dev-C++] Simplification for my code please
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Paul I. <pi...@ot...> - 2003-10-19 18:31:32
|
OROSZI Bal=E1zs <or...@vp...>:
> Coosa wrote:
> > I had today a lab test in C++ and one of the 10 questions was to writ=
e a=20
> > program which accepts a string input and reverse the words separately=
=20
> > between spaces and outputs it to the stream. I couldn=92t solve it in=
time=20
> > and I lost the marks for this section and went home and solved it.
>=20
> I GUESS this exercise could be a typical use of stack and stack=20
> operations: push, pop.
> First, have a stack implemented, which can handle arbitrary size, also=20
> implement push and pop. The rest of the task is simple:
> (draft)
>=20
> ch =3D read character;
> if (ch =3D=3D space){
> write each stack character using pop();
> write whitespace;
> }
> else{
> push(ch);
> }
>=20
> 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=
=20
> can extend the first "if" statement, like:
> if (ch =3D=3D space || ch =3D=3D tab || ch =3D=3D newline, ...)
>=20
> 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.
>=20
> Both read from stdin and write to stdout (redirect if you need). They=20
> read until EOF is read. Both are simple C programs, no C++ here. The=20
> stack implementation is primitive, no checking performed, however there=
=20
> should be no problem of that, due to the known use of the stack.
>=20
> Hope they help.
>=20
> --
> Greetings,
> Bal=E1zs
>=20
Agree, but why so complicated? The processor stack works fine in many cas=
es.
static char *str;
static int idx;
reverseWords(char ch, depth)
{
if ( ch =3D=3D ' ' || ch =3D=3D '\0' || ch =3D=3D <other blanks>)
{
return;
}
reverseWords(str[idx++], depth + 1);
cout << ch;
if (depth =3D=3D 0 && ch !=3D '\0')
{
cout << ' ';
reverseWords(str[idx++], 0)
}
}
call function with str -> read string, then
depth =3D 0;idx =3D 0;reverseWords(str[idx++], 0);
/Paul
|