do...while

This is a discussion on do...while within the C++ Programming forums, part of the General Programming Boards category; I thought I understood the tutorial well enough, but I keep getting an error when I try to compile. The ...

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    20

    do...while

    I thought I understood the tutorial well enough, but I keep getting an error when I try to compile. The error states "20 C:\transfer\cpp\junk\main.cpp `lm' undeclared (first use this function) " Dev-cpp highlights the line including
    Code:
        } while (lm == 1);
    when referencing this error. Thank you for your help. PS: trying to compile on win xp pro with dev-cpp 4.9.9.2

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main(int argc, char *argv[])
    {
        do {    
            int number; 
            int lm = 0;
            system("clear");
            cout<<"Enter a number between 1 and 10: ";
            cin>>number;
            for (int cntr = 1; cntr <= number; cntr++)
            {
                cout<<cntr<<"\n";
            }
            cout<<"\n\n";
            cout<<"Go Again?\n1. Yes\n2. No\n";
            cin>>lm;
        } while (lm == 1);
        cout<<"\n\n\n\n";
        system("Pause");
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Move the declaration outside the loop.
    Code:
        int lm = 0;
        do {
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    20
    Wonderful, thank you so much. BTW, is this a common way to loop the main section of a program? Do many other programmers do it this way? It seems suited perfectly for that use.

  4. #4
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,263
    Quote Originally Posted by m.mixon View Post
    Wonderful, thank you so much. BTW, is this a common way to loop the main section of a program? Do many other programmers do it this way? It seems suited perfectly for that use.
    It's pretty standard, but for clarity it is often better to break the actual loop body into its own function.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21