How to skip parts of a loop?

Apr 15, 2011 at 5:47pm
So I have some code that reads from a tab delimited file every value, and inputs those values into a string array. I then have a function that will take string input from the user and scan the array for a match. When it finds the result I then run a for loop to cout the next 80 variables. What I want to do is if any of the 80 values are "Null" or blank "", to skip them and continue the loop to the next variable. My code compiles, but does not run the way I intend.

I'm still new to c++, so take it easy on me! Here's the code, and I can provide the rest if neccessary:

1
2
3
4
5
6
7
8
9
10
11
12
13
            for(int j = 0 ; j < 80 ;j++)
            {
                if (masterMonstersDB[i+j] != "Null","")
                {
                    cout<<masterMonstersHeader[j];
                    cout<<masterMonstersDB[i+j]<<endl<<endl;
                };

                if (masterMonstersDB[i+j] == "Null","")
                {
                    continue;
                };
            };


If you could illuminate my issue it would be greatly appreciated!

P.S. Yay first post :3
Apr 15, 2011 at 5:54pm
When you use the comma operator like that on lines 3 and 9, it just evaluates to "". The way is works is, it evaluates all the expressions and returns the last:
1
2
3
int a = 7;
int b = (a+=3, 5, 99);
cout << a << ' ' << b;
10 99


What you want is this for line 3:
if(masterMonstersDB[i+j] != "Null" && masterMonstersDB[i+j] != "")
and line 9:
if(masterMonstersDB[i+j] == "Null" || masterMonstersDB[i+j] == "") or use an else, as Disch so rightfully said below this post.
Last edited on Apr 15, 2011 at 6:02pm
Apr 15, 2011 at 5:57pm
You can't use the comma operator like that. You need to do this:

1
2
3
4
5
6
7
for(int j = 0; j < 80; ++j)
{
  if(masterMonstersDB[i+j] != "Null" && masterMonstersDB[i+j] != "")
  {
    // output monsters
  }
}


Other notes:
- don't put semicolons after braces (ie: };) on control statement like if, for, etc. It doesn't hurt you here, but it will hurt you when you try to add else conditions. Only put }; when you're creating a new type or variable, like a class, struct, array or enum.

- no need for the 2nd if block. It's redundant and forces you to duplicate code.
Apr 15, 2011 at 6:19pm
1
2
3
4
5
6
7
8
for(int j = 0 ; j < 80 ;j++)
            {
                if (masterMonstersDB[i+j] != "NULL" && masterMonstersDB[i+j] != "")
                {
                    cout<<masterMonstersHeader[j];        //This line prints the header for the value
                    cout<<masterMonstersDB[i+j]<<endl<<endl;    //This line follows the header, printing the string value
                }
            }


This is the code I'm using now, and it's working great. Thanks a lot for the help :)
Topic archived. No new replies allowed.