Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 982
Stumbler Avatar asked Sep 09 '26 12:09

Stumbler


2 Answers

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.

like image 188
P.P Avatar answered Sep 11 '26 00:09

P.P


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.

like image 20
Dancrumb Avatar answered Sep 11 '26 01:09

Dancrumb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!