1
cout << "Type in your third message below:\n";
getline(cin, msgth);
if (msgth.length() > 0 && msgth.length() < 500) {}
else 
{
    system("cls");
    cout << "Your message has to be between 1 and 500 characters long...";
    goto prot;
}

So, whenever I get to this piece of code, it's like it automatically presses return, and "skips" the getline() function (AKA, goes to the prot label). The same thing happens further up for some reason. However, after a bit of experimenting, I've found out that when using this:

input:
if (special == 0)
{
    cout << "Choose your input message below:\n";
    getline(cin, inp);
    if (inp.length() > 0 && inp.length() < 500) {}
    else 
    {
        system("cls");
        cout << "Your message needs to be between 1 and 500 characters long\n";
        goto input;
    }
}

It does work the second time (with other words, after going to the input label). The difference between these two codes is that the first one has to bypass a std::cin code before getting back to getline(), while the other one doesn't.
A solution and some explaination would be gladly appreciated.

Max
  • 897
  • 1
  • 10
  • 27
  • goto makes code hard to understand/follow. Basically don't use it. – Kakalokia Nov 01 '13 at 11:48
  • Never use goto. That's what. But that's not causing your issue. – Grimm The Opiner Nov 01 '13 at 11:49
  • Actually, I like using it a lot. However, I'll go a head and add a non-goto based example aswell. – Max Nov 01 '13 at 11:49
  • 1
    @Max You may like using it, and you may understand what you're using, but other people won't. – Kakalokia Nov 01 '13 at 11:51
  • @Max Don't sweat it, leave the question as it is. Still, bear in mind that `goto` is very rarely the right tool for the job and it's frowned upon by most people. Anyway, the answer to your question is [here](http://stackoverflow.com/questions/6642865/getline-not-asking-for-input). – jrok Nov 01 '13 at 11:51
  • Okay, I'll leave it as it is. Was just worried of that people wouldn't understand. Regardless, enough of `goto`... – Max Nov 01 '13 at 11:53
  • Do you use `cin` with `operator>>` somewhere before this code? i.e. `cin >> something;` – Benjamin Lindley Nov 01 '13 at 13:37

1 Answers1

0

The following works for me:

#include <iostream>
#include <string>

int main() {
  std::string str;
start:
  std::cout << "prompt:\n";
  std::getline(std::cin, str);
  if (0 < str.length() && str.length() < 20) {}
  else {
    std::cout << "invalid.\n";
    goto start;
  }
  std::cout << "input: \"" << str << "\"\n";
}

How is yours different from this?

Adam Burry
  • 1,904
  • 13
  • 20