Thread: Help with loops

  1. #16
    Registered User
    Join Date
    Sep 2001
    Posts
    4,912
    endl puts a newline character in the output stream and flushes it.

  2. #17
    Registered User
    Join Date
    Jun 2005
    Posts
    17
    well theres quite a few different kinds of loops. sometimes wed have wierd projects... and would require it to run once, but depending on some argument wed have to run a certain ammount of times. for example...

    Code:
    x=10;
    do {
    cout << "blahblahblah" << endl;
    x--;
    }while(x!=0);
    this will run the loop once... THEN get to the argument... if the argument is still true... it will run the loop again... if its false it will end... also note anything other than 0 inside of the () is considered true. ex while(9); is an endless loop until the program is stopped or a break; is called.


    there is the counter part of this:
    Code:
    while(x!=0){
    x--;
    cout << "i like toes" << endl;
    }
    and a personal fave...
    Code:
    for(i=0;i<10;i++){
    cout << "moooooo" << endl;
    }
    the syntax for the for loop is: (set you var to whatever;limit;incriment) which is why i set my var to 0, told it to run till it was 10 or higher, and every time it loops add 1 to i.

    hopefully that helped a bit

  3. #18
    ------------
    Join Date
    Jun 2005
    Posts
    79
    Ok some more examples im making right now to make sure i know this... (im not looking at the tutorial or any other code this time! )

    while:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int x = 100;
    
    	while ( x != 0 ) {
    		x--;
    		cout<<"You are at "<<x<<".\n";
    	}
    }
    do-while:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int x = 100;
    
    	do {
    		x--;
    		cout<<"You are at "<<x<<".\n";
    	}
    	while ( x != 0 );
    }
    for:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int x = 100;
    
    	for ( x = 100; x != 0; x-- ) {
    		cout<<"You are at " << x <<".\n";
    	}
    }
    i think im getting it (well... i kind of cheated on the "for" loop... couldnt remember the syntax for it)

    edit:
    do i have to put that first
    Code:
    int x = 100;
    in there? or is that covered by the
    Code:
    for ( x = 100; x != 0; x-- )
    ??
    Last edited by Goosie; 06-22-2005 at 12:00 PM. Reason: adding question
    CAUTION: Newbie at programming!
    -------------------------------------------------
    Thanks everyone who helped me with all the questions, and utter lost-ness i happen to have... it is VERY VERY much appreciated

  4. #19
    ------------
    Join Date
    Jun 2005
    Posts
    79
    Ok, one more... this one uses a pointer and a while loop

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	int a;
    	int *b;
    
    	b = &a;
    
    	cout<<"Enter a number 1-100: ";
    	cin>>a;
    	
    	while ( a == 0 || a >= 101 ) {
    	cout<<"Invalid number, try again: ";
    	cin>>a;
    	}
    
    	cout<<"You picked: " << *b <<".\n";
    }
    but how do i make it so it repeats "invalid number, try again" if they just press enter and not enter a number?
    CAUTION: Newbie at programming!
    -------------------------------------------------
    Thanks everyone who helped me with all the questions, and utter lost-ness i happen to have... it is VERY VERY much appreciated

  5. #20
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    >>do i have to put that first?

    No. You just need to be sure i is declared and initialized before you use it. In addition to the syntax you used, which is ok,

    for(int i = 100; i != 0; --i)

    will work, as will

    int i;
    for(i = 100; i != 0; --i)

    as will

    int i = 100;
    for( ; i != 0; --i)
    You're only born perfect.

  6. #21
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    >>how do i make it so it repeats "invalid number, try again" if they just press enter and not enter a number

    You could try to initialize the variable a to a value that is known to be invalid to begin with. Or you could do data validation, such as reading the state of the stream after attempting input or inputting all data into a string and then validating the input before converting it to an int.

    For now I'd assume valid input so you learn syntax and program flow first. When you feel comfortable with that, then you try your hand a validation techniques. They can be tricky, depending on what you are trying to validate. Validation techniques are common questions, so if you really want to persue it now you can search the board.
    You're only born perfect.

  7. #22
    ------------
    Join Date
    Jun 2005
    Posts
    79
    lol by the sounds of what you just said and me not understanding any of it, i'll just wait till later to try that... thanks for the help
    CAUTION: Newbie at programming!
    -------------------------------------------------
    Thanks everyone who helped me with all the questions, and utter lost-ness i happen to have... it is VERY VERY much appreciated

  8. #23
    Its hard... But im here swgh's Avatar
    Join Date
    Apr 2005
    Location
    England
    Posts
    1,688
    I would like to add that I agree with all of you guys who said GOTO is a bad loop to use, I know this is a BASIC example, but it would work the same in C and C++, it is just a LAZY way to avoid using and learning how functions work...

    Example:

    print"Where do you want to go?"
    print ' leave blank'
    print"For home press h"
    print"For office press o"
    input a$

    if a$ = "h" GOTO home
    else if a$ = "o" then GOTO office

    [home]
    print ' text'

    [office]
    print 'text'

    end


    Anyway, the above shows us just how horrible the goto was in BASIC. I know that the use of GOTO is a good thing to have if you are an experienced programmer, and it does have its uses. But in general, I would avise all to ignore it, untill you know how to use it in the best possilble situation. Functions used in C and C++ are much nicer to look at, and keep code flowing well and are easy to understand when you learn them.!!!

  9. #24
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    What is interesting about it is that if you enter a letter it will flip out and print that cout a zillion times, and ignore the cin.. it wont even call that cin. The actual interesting part of that is that if you print what a is equal to, it says 0, so it shouldnt be flipping out, not only that but if you assign a = 0; in the while loop to ensure it doesnt flip out, it still does. So you'd think it must just be going through a spaz phase where it isnt responding, but it is, if you put a = 65; at the end of the while loop, it will exit. So this leaves only to conclude the cin breaks when you enter something that doesnt fit to the variable and wont let you call it again. Any ideas?
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

  10. #25
    Registered User
    Join Date
    Jun 2005
    Posts
    32
    Cin has very lazy input validation, when you use cin and input a char it doesn't automatically convert it to an int for you, or god forbid you type in a string.

    There are several methods you can use for input validation, the eaisest (if your dealing with integers) is to use the cctype function isdigit(). Which takes the parameter of a single char. and returns of it is infact a digit or not.

    so you could do somthing like the following.

    Code:
    bool badinput=false;
    char *str = new char[512];
    cin>>str;
    for(int i =0;i<strlen(str);i++)
    {
       if(!isdigit(str[i]))//This isn't a digit!!
           badinput=true;
    }
    
    while(badinput)
    {
       cout<<"enter a NUMBER please"<<endl;
       cin>>str;
        
       for(int i =0;i<strlen(str);i++) 
       { 
           if(!isdigit(str[i])){//This isn't a digit!!
           badinput=true;
           continue;
           }
           badinput=false;
        }
       //EDIT: oops forgot to terminate my loop!
    }
    I suppose you could just assume the input is bad at first and save yourself the extra call to the for loop. but you get the point.

    Btw i didn't test this, iirc isdigit returns 1 if it is a number. if not, just remove the ! and it should work.

    EDIT: forgot to terminate the loop... why does it look so funny to me when i read it over??? It should work <shrug>.
    Last edited by Charmy; 06-23-2005 at 08:37 AM.

  11. #26
    Deprecated Dae's Avatar
    Join Date
    Oct 2004
    Location
    Canada
    Posts
    1,034
    Quote Originally Posted by Charmy
    Cin has very lazy input validation, when you use cin and input a char it doesn't automatically convert it to an int for you, or god forbid you type in a string.
    Thats true but his code flips the hell out when you enter a char, which it shouldnt because the value didnt change. (confirmed by printing the value after). So it should just continue onto the next loop and ask for input again, which it will do if you enter 0, but when you enter a character it flips out.. even though when you enter a char its still 0. I dont expect it to do any sort of converting, but it should ask for input again shouldnt it? Entering a letter to a cin that tries to input it into an int completely disables cin from being used again.
    Warning: Have doubt in anything I post.

    GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101

  12. #27
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Quote Originally Posted by Dae
    So this leaves only to conclude the cin breaks when you enter something that doesnt fit to the variable and wont let you call it again. Any ideas?
    Indeed, if you try to enter a letter into an int cin will "break", except I believe the technical term is that cin will "fail", which then leads to the concept of a "failed state". It turns out that streams such as cin do have an attribute called state, which is determined by evaluating the state bit. If the state bit is in the failed state, then nothing will be put into the variable. In order to use cin again once it has entered the failed state you need to reset the state bit, that is you have to "clear" the failed state.

    It also turns out you can evaluate the state of the stream by using the good() or the fail() methods. If the stream is in the failed state you can reset the state/fail bit by using the clear() method, and you can ignore the material in the input buffer that caused the failed state by using the ignore() method.

    So, if you enter a char other than a digit when attempting to enter data into an int, cin will fail and the state/fail bit will be set to the failed state. Most of the time newbies, and those of us more interested in the process rather than the product, don't bother to check the stream state after attempting input---we assume appropriate input, because data validation is a pain in the ___. However, to make a robust program, it's what you need to do.

    Here's an example of how you might try to vaidate input using stream states. I don't usually do it as I'm not in the habit of writing programs for other people so I don't doubt that there is some imperfection in the syntax somewhere, but the concepts are real.
    Code:
    int i;
    std::cin >> i;
    if(std::cin.fail())  //check the state of the stream after attempted input
    {
      std::cout << "invalid input" << std::endl; 
      std::cin.clear(); //clear the fail bit 
      std::cin.ignore(std::numeric_limits<std::streamsize>::max());  //since you don't know what caused the failure ignore as many char as a given stream can hold.
    }
    If you don't like checking the stream state to validate input, then you can never accept input into a variable type other than a string, as there is no such thing as an invalid string. Then, instead of evaluating the stream state you need to validate that each char in the string is valid and in a valid sequence before converting the string to the type of variable desired. This is the type of validation that Chamy demonstrated.
    You're only born perfect.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Too many loops D:
    By F5 Tornado in forum C++ Programming
    Replies: 6
    Last Post: 12-03-2007, 01:18 AM
  2. loops with incrementing strings .... ?
    By twomers in forum C++ Programming
    Replies: 1
    Last Post: 12-12-2005, 11:29 AM
  3. Evaluation of nested loops
    By Mister C in forum C Programming
    Replies: 2
    Last Post: 08-13-2004, 01:47 PM
  4. recoursion or loops?
    By Mecnels in forum C++ Programming
    Replies: 2
    Last Post: 01-14-2002, 12:09 PM
  5. help with arrays and loops
    By jdiazj1 in forum C Programming
    Replies: 4
    Last Post: 11-24-2001, 04:28 PM