Infinite while loop

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • madafaka
    New Member
    • Apr 2010
    • 2

    Infinite while loop

    guys i am this term i am taking basic c++ course and in this homework, i encountered an infinite loop problem and i dont know how to fix it. i am pretty sure that it is an easy problem for you, so if you help, i will appreciate it. so here is the problem;

    in here i have to make an input check to see that if the user enters a string longer than 39 characters.

    #include <iostream>
    #include <string>
    using namespace std;

    int main()
    {
    string scrambledText;

    cout << "Scrambled Text: ";
    cin >> scrambledText;

    int i = scrambledText.l ength();

    if (i < 40)
    {
    while (i < 40)
    {
    cout << "Input string must be longer than 40 characters" << endl ;
    }
    }
    return 0;
    }

    but when i run the program it keeps writing "Input string must be longer than 40 characters". so i dont want it obviously :) what i want is, to go to the beginning and let the user input anoter string again. i really need your help. thx
  • akdemirc
    New Member
    • Sep 2008
    • 26

    #2
    have a look at do-while loop, it is more convenient in your case, simply force user to input as long as it has a length < 40

    do
    {
    cout << "Scrambled Text: ";
    cin >> scrambledText;

    }while (scrambledText. length < 40);

    // here you will get scrambledText.l ength > 40

    Comment

    • madafaka
      New Member
      • Apr 2010
      • 2

      #3
      it worked :) thank you so much

      Comment

      Working...