Avoid bad user input (string when what's asked is an integer)Convert a string to an integer in JavaScript?Java - Convert integer to stringchecking for user integer input with cin gives infinite loopWhy does this code involving cin skip getline even with cin.ignore()?Resseting cin stream state c++C++, User input of letters, numbers, and spaces into a stringWhy cin inside while doesn't stop to get user input?C++ getline is not empty when no input is enteredIssue When Clearing cin Buffer After Using cin.getline()Program is saving every time the user presses enter, and spitting it out when cin is called

In The Incredibles 2, why does Screenslaver's name use a pun on something that doesn't exist in the 1950s pastiche?

Placement of positioning lights on A320 winglets

How to generate list of *all* available commands and functions?

Is it safe to dpkg --set-selections on a newer version of a distro?

How to Handle Many Times Series Simultaneously?

Can a Warforged suffer from magical exhaustion?

How to make a composition of functions prettier?

How can you estimate a spike story?

How many sets of dice do I need for D&D?

What plausible reason could I give for my FTL drive only working in space

Is it advisable to add a location heads-up when a scene changes in a novel?

How to represent jealousy in a cute way?

post-head emotive modifiers such as "in the world" and "the hell"

ASCII Meme Arrow Generator

Does it make sense to use a wavelet that is equal to a sine of one period?

How does AFV select the winning videos?

Why do the TIE Fighter pilot helmets have similar ridges as the rebels?

Why are ambiguous grammars bad?

Cahn–Ingold–Prelog Rules, cyclic structures, and breaking ties

What is this object?

What does this line mean in Zelazny's "The Courts of Chaos"?

Why would a home insurer offer a discount based on credit score?

Why does there seem to be an extreme lack of public trashcans in Taiwan?

How can I find out about the game world without meta-influencing it?



Avoid bad user input (string when what's asked is an integer)


Convert a string to an integer in JavaScript?Java - Convert integer to stringchecking for user integer input with cin gives infinite loopWhy does this code involving cin skip getline even with cin.ignore()?Resseting cin stream state c++C++, User input of letters, numbers, and spaces into a stringWhy cin inside while doesn't stop to get user input?C++ getline is not empty when no input is enteredIssue When Clearing cin Buffer After Using cin.getline()Program is saving every time the user presses enter, and spitting it out when cin is called






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have an infinite while loop, where the user is asked for a number.



My problem is very simple: If the input is a string, I want to re-ask user for input, outputting the message "Enter a valid choice: ".



I searched, and looks like I should check for cin.fail(), then call cin.clear() and cin.ignore().



Here's my code:



int main() 
int choice;
bool failed = false;
while (true)
if (failed) cout << "Enter a valid choice: ";
else cout << "Enter a number: ";
cin >> choice;

if (cin.fail())
cin.clear();
cin.ignore();
failed = true;



return 0;



However, this doesn't really fix my problem. Of course, it isn't printing infinitely, but for each letter extra letter , it prints another "Enter a valid choice:"



Seems like I need to call cin.ignore() for each extra letter.



Any other way of doing this?










share|improve this question

















  • 1





    Rather trivial blog post of mine which may still be helpful: latedev.wordpress.com/2011/09/13/…

    – Neil Butterworth
    Mar 24 at 22:44







  • 1





    @NeilButterworth This was EXACTLY what I needed. I didn't want to create a for loop to cin.ignore(), but this numeric_limits<int>::max() is perfect. Make it a real answer and I'll accept it. Thank you very much.

    – Nyck
    Mar 24 at 22:50

















1















I have an infinite while loop, where the user is asked for a number.



My problem is very simple: If the input is a string, I want to re-ask user for input, outputting the message "Enter a valid choice: ".



I searched, and looks like I should check for cin.fail(), then call cin.clear() and cin.ignore().



Here's my code:



int main() 
int choice;
bool failed = false;
while (true)
if (failed) cout << "Enter a valid choice: ";
else cout << "Enter a number: ";
cin >> choice;

if (cin.fail())
cin.clear();
cin.ignore();
failed = true;



return 0;



However, this doesn't really fix my problem. Of course, it isn't printing infinitely, but for each letter extra letter , it prints another "Enter a valid choice:"



Seems like I need to call cin.ignore() for each extra letter.



Any other way of doing this?










share|improve this question

















  • 1





    Rather trivial blog post of mine which may still be helpful: latedev.wordpress.com/2011/09/13/…

    – Neil Butterworth
    Mar 24 at 22:44







  • 1





    @NeilButterworth This was EXACTLY what I needed. I didn't want to create a for loop to cin.ignore(), but this numeric_limits<int>::max() is perfect. Make it a real answer and I'll accept it. Thank you very much.

    – Nyck
    Mar 24 at 22:50













1












1








1








I have an infinite while loop, where the user is asked for a number.



My problem is very simple: If the input is a string, I want to re-ask user for input, outputting the message "Enter a valid choice: ".



I searched, and looks like I should check for cin.fail(), then call cin.clear() and cin.ignore().



Here's my code:



int main() 
int choice;
bool failed = false;
while (true)
if (failed) cout << "Enter a valid choice: ";
else cout << "Enter a number: ";
cin >> choice;

if (cin.fail())
cin.clear();
cin.ignore();
failed = true;



return 0;



However, this doesn't really fix my problem. Of course, it isn't printing infinitely, but for each letter extra letter , it prints another "Enter a valid choice:"



Seems like I need to call cin.ignore() for each extra letter.



Any other way of doing this?










share|improve this question














I have an infinite while loop, where the user is asked for a number.



My problem is very simple: If the input is a string, I want to re-ask user for input, outputting the message "Enter a valid choice: ".



I searched, and looks like I should check for cin.fail(), then call cin.clear() and cin.ignore().



Here's my code:



int main() 
int choice;
bool failed = false;
while (true)
if (failed) cout << "Enter a valid choice: ";
else cout << "Enter a number: ";
cin >> choice;

if (cin.fail())
cin.clear();
cin.ignore();
failed = true;



return 0;



However, this doesn't really fix my problem. Of course, it isn't printing infinitely, but for each letter extra letter , it prints another "Enter a valid choice:"



Seems like I need to call cin.ignore() for each extra letter.



Any other way of doing this?







c++ string int cin cout






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 24 at 22:35









NyckNyck

8218




8218







  • 1





    Rather trivial blog post of mine which may still be helpful: latedev.wordpress.com/2011/09/13/…

    – Neil Butterworth
    Mar 24 at 22:44







  • 1





    @NeilButterworth This was EXACTLY what I needed. I didn't want to create a for loop to cin.ignore(), but this numeric_limits<int>::max() is perfect. Make it a real answer and I'll accept it. Thank you very much.

    – Nyck
    Mar 24 at 22:50












  • 1





    Rather trivial blog post of mine which may still be helpful: latedev.wordpress.com/2011/09/13/…

    – Neil Butterworth
    Mar 24 at 22:44







  • 1





    @NeilButterworth This was EXACTLY what I needed. I didn't want to create a for loop to cin.ignore(), but this numeric_limits<int>::max() is perfect. Make it a real answer and I'll accept it. Thank you very much.

    – Nyck
    Mar 24 at 22:50







1




1





Rather trivial blog post of mine which may still be helpful: latedev.wordpress.com/2011/09/13/…

– Neil Butterworth
Mar 24 at 22:44






Rather trivial blog post of mine which may still be helpful: latedev.wordpress.com/2011/09/13/…

– Neil Butterworth
Mar 24 at 22:44





1




1





@NeilButterworth This was EXACTLY what I needed. I didn't want to create a for loop to cin.ignore(), but this numeric_limits<int>::max() is perfect. Make it a real answer and I'll accept it. Thank you very much.

– Nyck
Mar 24 at 22:50





@NeilButterworth This was EXACTLY what I needed. I didn't want to create a for loop to cin.ignore(), but this numeric_limits<int>::max() is perfect. Make it a real answer and I'll accept it. Thank you very much.

– Nyck
Mar 24 at 22:50












2 Answers
2






active

oldest

votes


















1














You have an infinite loop because you are not breaking the loop even when valid input is enter. Is that what you really want? If so, at the least, you are not resetting the failed flag in valid input.



More importantly, when invalid input is entered, you are not ignoring everything that was enteted, you are only ignoring 1 char at a time. That is why you see extra prompts.



Try this instead :



int main() 
int choice;
while (true)
cout << "Enter a number: ";
while (!(cin >> choice))
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
cout << "Enter a valid choice: ";


return 0;






share|improve this answer






























    0














    The reason it is printing so many times is because you are only clearing the state of cin, but aren't clearing the input buffer. You can do so in multiple ways:-



    1. Use fflush(stdin) to clear the input buffer.This is the C method and can be done by including cstdio header.


    2. Use the cin.ignore to ignore all characters in the current input stream. You can do this by replacing the line cin.ignore() which ignores a single character by this code cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n') which ignores the entire line. For this you need the limits header.


    3. Finally you can do the same with a simple loop like while (cin.get() != 'n')continue; which ignores all characters till new line.


    Also another approach to the same problem is to take the input in form of a string and use the strtol() or the isdigit() functions to check if the input is valid.



    By the way the infinite loop is because you have not used the break statement to terminate the loop. So you can avoid this by adding



    if(!failed)
    break;


    Also you need to change the state of Failed at the entry of each loop by adding



    failed=false;


    at the start of the loop body.






    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55329242%2favoid-bad-user-input-string-when-whats-asked-is-an-integer%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      You have an infinite loop because you are not breaking the loop even when valid input is enter. Is that what you really want? If so, at the least, you are not resetting the failed flag in valid input.



      More importantly, when invalid input is entered, you are not ignoring everything that was enteted, you are only ignoring 1 char at a time. That is why you see extra prompts.



      Try this instead :



      int main() 
      int choice;
      while (true)
      cout << "Enter a number: ";
      while (!(cin >> choice))
      cin.clear();
      cin.ignore(numeric_limits<streamsize>::max(), 'n');
      cout << "Enter a valid choice: ";


      return 0;






      share|improve this answer



























        1














        You have an infinite loop because you are not breaking the loop even when valid input is enter. Is that what you really want? If so, at the least, you are not resetting the failed flag in valid input.



        More importantly, when invalid input is entered, you are not ignoring everything that was enteted, you are only ignoring 1 char at a time. That is why you see extra prompts.



        Try this instead :



        int main() 
        int choice;
        while (true)
        cout << "Enter a number: ";
        while (!(cin >> choice))
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), 'n');
        cout << "Enter a valid choice: ";


        return 0;






        share|improve this answer

























          1












          1








          1







          You have an infinite loop because you are not breaking the loop even when valid input is enter. Is that what you really want? If so, at the least, you are not resetting the failed flag in valid input.



          More importantly, when invalid input is entered, you are not ignoring everything that was enteted, you are only ignoring 1 char at a time. That is why you see extra prompts.



          Try this instead :



          int main() 
          int choice;
          while (true)
          cout << "Enter a number: ";
          while (!(cin >> choice))
          cin.clear();
          cin.ignore(numeric_limits<streamsize>::max(), 'n');
          cout << "Enter a valid choice: ";


          return 0;






          share|improve this answer













          You have an infinite loop because you are not breaking the loop even when valid input is enter. Is that what you really want? If so, at the least, you are not resetting the failed flag in valid input.



          More importantly, when invalid input is entered, you are not ignoring everything that was enteted, you are only ignoring 1 char at a time. That is why you see extra prompts.



          Try this instead :



          int main() 
          int choice;
          while (true)
          cout << "Enter a number: ";
          while (!(cin >> choice))
          cin.clear();
          cin.ignore(numeric_limits<streamsize>::max(), 'n');
          cout << "Enter a valid choice: ";


          return 0;







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 24 at 22:54









          Remy LebeauRemy Lebeau

          351k19277474




          351k19277474























              0














              The reason it is printing so many times is because you are only clearing the state of cin, but aren't clearing the input buffer. You can do so in multiple ways:-



              1. Use fflush(stdin) to clear the input buffer.This is the C method and can be done by including cstdio header.


              2. Use the cin.ignore to ignore all characters in the current input stream. You can do this by replacing the line cin.ignore() which ignores a single character by this code cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n') which ignores the entire line. For this you need the limits header.


              3. Finally you can do the same with a simple loop like while (cin.get() != 'n')continue; which ignores all characters till new line.


              Also another approach to the same problem is to take the input in form of a string and use the strtol() or the isdigit() functions to check if the input is valid.



              By the way the infinite loop is because you have not used the break statement to terminate the loop. So you can avoid this by adding



              if(!failed)
              break;


              Also you need to change the state of Failed at the entry of each loop by adding



              failed=false;


              at the start of the loop body.






              share|improve this answer





























                0














                The reason it is printing so many times is because you are only clearing the state of cin, but aren't clearing the input buffer. You can do so in multiple ways:-



                1. Use fflush(stdin) to clear the input buffer.This is the C method and can be done by including cstdio header.


                2. Use the cin.ignore to ignore all characters in the current input stream. You can do this by replacing the line cin.ignore() which ignores a single character by this code cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n') which ignores the entire line. For this you need the limits header.


                3. Finally you can do the same with a simple loop like while (cin.get() != 'n')continue; which ignores all characters till new line.


                Also another approach to the same problem is to take the input in form of a string and use the strtol() or the isdigit() functions to check if the input is valid.



                By the way the infinite loop is because you have not used the break statement to terminate the loop. So you can avoid this by adding



                if(!failed)
                break;


                Also you need to change the state of Failed at the entry of each loop by adding



                failed=false;


                at the start of the loop body.






                share|improve this answer



























                  0












                  0








                  0







                  The reason it is printing so many times is because you are only clearing the state of cin, but aren't clearing the input buffer. You can do so in multiple ways:-



                  1. Use fflush(stdin) to clear the input buffer.This is the C method and can be done by including cstdio header.


                  2. Use the cin.ignore to ignore all characters in the current input stream. You can do this by replacing the line cin.ignore() which ignores a single character by this code cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n') which ignores the entire line. For this you need the limits header.


                  3. Finally you can do the same with a simple loop like while (cin.get() != 'n')continue; which ignores all characters till new line.


                  Also another approach to the same problem is to take the input in form of a string and use the strtol() or the isdigit() functions to check if the input is valid.



                  By the way the infinite loop is because you have not used the break statement to terminate the loop. So you can avoid this by adding



                  if(!failed)
                  break;


                  Also you need to change the state of Failed at the entry of each loop by adding



                  failed=false;


                  at the start of the loop body.






                  share|improve this answer















                  The reason it is printing so many times is because you are only clearing the state of cin, but aren't clearing the input buffer. You can do so in multiple ways:-



                  1. Use fflush(stdin) to clear the input buffer.This is the C method and can be done by including cstdio header.


                  2. Use the cin.ignore to ignore all characters in the current input stream. You can do this by replacing the line cin.ignore() which ignores a single character by this code cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n') which ignores the entire line. For this you need the limits header.


                  3. Finally you can do the same with a simple loop like while (cin.get() != 'n')continue; which ignores all characters till new line.


                  Also another approach to the same problem is to take the input in form of a string and use the strtol() or the isdigit() functions to check if the input is valid.



                  By the way the infinite loop is because you have not used the break statement to terminate the loop. So you can avoid this by adding



                  if(!failed)
                  break;


                  Also you need to change the state of Failed at the entry of each loop by adding



                  failed=false;


                  at the start of the loop body.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 25 at 8:08

























                  answered Mar 24 at 23:14









                  Captain ClawCaptain Claw

                  93




                  93



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55329242%2favoid-bad-user-input-string-when-whats-asked-is-an-integer%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                      Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript