Stumbler
Stumbler

Reputation: 2146

for loop not operating

I came up with what I thought was a messy solution to an awkward (albeit standard) problem: For a given user input, reverse the letters of the words

E.g:

This is a standard test

becomes

sihT si a dradnats tset

and not

tset dradnats a si sihT

The heart of the matter is this piece of code

  while (!iscntrl(user_input[x])) // quit when new line is read
      {
        restart:
        x++;
        puts("first level test");
        if (user_input[x]==' ')
            {
            puts("second level test");
            for (i=x; user_input[i]!=' '; --i)
                {               
                reverse_words[k]=user_input[i];
                k++;
                puts("third level test");
                goto restart;
                }
            }
        }

(yes, I know, there is a goto in there :/ )

but the third level of the loop is never touched.

Presumably there is something completely wrong with (i=x; user_input[i]!=' '; --i) as a for loop parameter?

x, i, and k are all initialised as integers == 0 prior to the beginning of the first loop.

Upvotes: 3

Views: 115

Answers (2)

Dancrumb
Dancrumb

Reputation: 27529

The problem is this section:

 if (user_input[x]==' ')
            {
            puts("second level test");
            for (i=x; user_input[i]!=' '; --i)
                {               

In the first line, you've established that user_input[x]==' '.

A few lines later, you set up a loop that will run while user_input[i]!=' '.

However, you've set i = x... thus, in the first pass, you're requiring that user_input[x]!=' '... which you've already established to be false.

Thus, the inner loop will never run.

Upvotes: 2

P.P
P.P

Reputation: 121347

Well, your condition contradicts here:

 if (user_input[x]==' ')
            {
            puts("second level test");
            for (i=x; user_input[i]!=' '; --i)

You only enter if user_input[x] is space, but you loop as long as it's not equal to space.

Upvotes: 5

Related Questions