How to limit input from user to numbers and letters only in C++











up vote
-1
down vote

favorite












The program only needs numbers and/or letters as input from the user. otherwise, the program must be terminated. I don't know how to limit the input to numbers and letters only.



Here is my program:



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

int main()
{
string input, reversed = "";

cout << "Enter string: ";
cin >> input;

for (int i = input.length() - 1; i < input.length(); i--)
{
reversed += input[i];
}
cout << reversed << endl;

if (reversed == input) cout << "It is a palindrome!";
else cout << "No, it is not a palindrome!";
return 0;
}









share|improve this question




















  • 1




    Your for loop will never end, because in i < input.length() your i will always be lesser than input.length()
    – Rhathin
    Nov 8 at 14:16








  • 1




    I recommend you read about std::all_of, about lambda expressions, and about the standard character classification functions.
    – Some programmer dude
    Nov 8 at 14:16










  • take a look at the ascii table that may help you
    – Yastanub
    Nov 8 at 14:16










  • Maybe for (int i = input.length() - 1; i < input.length() ; i--) -> for (int i = input.length() - 1; i >= 0 ; i--)
    – Jabberwocky
    Nov 8 at 14:20






  • 1




    Or just use std::reverse for reversing the string?
    – Some programmer dude
    Nov 8 at 14:22















up vote
-1
down vote

favorite












The program only needs numbers and/or letters as input from the user. otherwise, the program must be terminated. I don't know how to limit the input to numbers and letters only.



Here is my program:



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

int main()
{
string input, reversed = "";

cout << "Enter string: ";
cin >> input;

for (int i = input.length() - 1; i < input.length(); i--)
{
reversed += input[i];
}
cout << reversed << endl;

if (reversed == input) cout << "It is a palindrome!";
else cout << "No, it is not a palindrome!";
return 0;
}









share|improve this question




















  • 1




    Your for loop will never end, because in i < input.length() your i will always be lesser than input.length()
    – Rhathin
    Nov 8 at 14:16








  • 1




    I recommend you read about std::all_of, about lambda expressions, and about the standard character classification functions.
    – Some programmer dude
    Nov 8 at 14:16










  • take a look at the ascii table that may help you
    – Yastanub
    Nov 8 at 14:16










  • Maybe for (int i = input.length() - 1; i < input.length() ; i--) -> for (int i = input.length() - 1; i >= 0 ; i--)
    – Jabberwocky
    Nov 8 at 14:20






  • 1




    Or just use std::reverse for reversing the string?
    – Some programmer dude
    Nov 8 at 14:22













up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











The program only needs numbers and/or letters as input from the user. otherwise, the program must be terminated. I don't know how to limit the input to numbers and letters only.



Here is my program:



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

int main()
{
string input, reversed = "";

cout << "Enter string: ";
cin >> input;

for (int i = input.length() - 1; i < input.length(); i--)
{
reversed += input[i];
}
cout << reversed << endl;

if (reversed == input) cout << "It is a palindrome!";
else cout << "No, it is not a palindrome!";
return 0;
}









share|improve this question















The program only needs numbers and/or letters as input from the user. otherwise, the program must be terminated. I don't know how to limit the input to numbers and letters only.



Here is my program:



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

int main()
{
string input, reversed = "";

cout << "Enter string: ";
cin >> input;

for (int i = input.length() - 1; i < input.length(); i--)
{
reversed += input[i];
}
cout << reversed << endl;

if (reversed == input) cout << "It is a palindrome!";
else cout << "No, it is not a palindrome!";
return 0;
}






c++ algorithm inputstream






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 8 at 20:09









JeJo

3,6143624




3,6143624










asked Nov 8 at 14:13









R. Yamamoto

111




111








  • 1




    Your for loop will never end, because in i < input.length() your i will always be lesser than input.length()
    – Rhathin
    Nov 8 at 14:16








  • 1




    I recommend you read about std::all_of, about lambda expressions, and about the standard character classification functions.
    – Some programmer dude
    Nov 8 at 14:16










  • take a look at the ascii table that may help you
    – Yastanub
    Nov 8 at 14:16










  • Maybe for (int i = input.length() - 1; i < input.length() ; i--) -> for (int i = input.length() - 1; i >= 0 ; i--)
    – Jabberwocky
    Nov 8 at 14:20






  • 1




    Or just use std::reverse for reversing the string?
    – Some programmer dude
    Nov 8 at 14:22














  • 1




    Your for loop will never end, because in i < input.length() your i will always be lesser than input.length()
    – Rhathin
    Nov 8 at 14:16








  • 1




    I recommend you read about std::all_of, about lambda expressions, and about the standard character classification functions.
    – Some programmer dude
    Nov 8 at 14:16










  • take a look at the ascii table that may help you
    – Yastanub
    Nov 8 at 14:16










  • Maybe for (int i = input.length() - 1; i < input.length() ; i--) -> for (int i = input.length() - 1; i >= 0 ; i--)
    – Jabberwocky
    Nov 8 at 14:20






  • 1




    Or just use std::reverse for reversing the string?
    – Some programmer dude
    Nov 8 at 14:22








1




1




Your for loop will never end, because in i < input.length() your i will always be lesser than input.length()
– Rhathin
Nov 8 at 14:16






Your for loop will never end, because in i < input.length() your i will always be lesser than input.length()
– Rhathin
Nov 8 at 14:16






1




1




I recommend you read about std::all_of, about lambda expressions, and about the standard character classification functions.
– Some programmer dude
Nov 8 at 14:16




I recommend you read about std::all_of, about lambda expressions, and about the standard character classification functions.
– Some programmer dude
Nov 8 at 14:16












take a look at the ascii table that may help you
– Yastanub
Nov 8 at 14:16




take a look at the ascii table that may help you
– Yastanub
Nov 8 at 14:16












Maybe for (int i = input.length() - 1; i < input.length() ; i--) -> for (int i = input.length() - 1; i >= 0 ; i--)
– Jabberwocky
Nov 8 at 14:20




Maybe for (int i = input.length() - 1; i < input.length() ; i--) -> for (int i = input.length() - 1; i >= 0 ; i--)
– Jabberwocky
Nov 8 at 14:20




1




1




Or just use std::reverse for reversing the string?
– Some programmer dude
Nov 8 at 14:22




Or just use std::reverse for reversing the string?
– Some programmer dude
Nov 8 at 14:22












3 Answers
3






active

oldest

votes

















up vote
2
down vote













The simplest way you can achieve what you want is checking every character. As @Pete Becker pointed out, you may use isalnum to check if the character is a number or a letter character:



#include <iostream>
#include <string>

int main () {
std::string s = "Hello W>orld";

for (auto c : s) {
if (!isalnum(c)) {
std::cout << "Found : '" << c << "'" << std::endl;
}
}

return 0;
}


Output:



Found : ' '
Found : '>'





share|improve this answer























  • Just for completeness, isalnum returns true when its argument is a letter or a number.
    – Pete Becker
    Nov 8 at 14:24










  • @PeteBecker Thanks for pointing out! Added that.
    – Ayxan
    Nov 8 at 14:30


















up vote
2
down vote













As @Someprogrammerdude mentioned in the comments, using std::all_of and an appropriate binary predicate(lambda function), you can do it easily as follows.



Secondly, for checking the string input to its reverse string, just create a temporary string using the reverse iterators of std::string and check it. That way, you do not need to have another variable.



Hope the comments will help you to understand more options.
SEE LIVE



#include <iostream>
#include <cctype> // std::isdigit and std::isalpha and std::isalnum
#include <string>
#include <algorithm> // std::all_of

int main()
{
std::string input; std::cin >> input;

const auto check = (const char eachCar)->bool{ return std::isalnum(eachCar); };
/* change return statement of lambda to
std::isdigit(eachCar) ---> for only digits
std::isalpha(eachCar) ---> for only letters
*/
if(std::all_of(input.cbegin(), input.cend(), check))
{
if(input == std::string(input.crbegin(), input.crend()))
std::cout << "It is a palindrome!";
else std::cout << "No, it is not a palindrome!";
}
return 0;
}


Input:



123kk321


Output:



It is a palindrome!





share|improve this answer






























    up vote
    1
    down vote













    Assume the input has no space, you can do like this:



    char c; string s; bool chk = true;
    while (cin >> c)
    {
    if (('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
    s.push_back(c);
    else chk = false;
    }
    if (chk == true) cout << "Valid string";
    else cout << "Invalid string";


    The above code will terminate when there is no character left in the input.






    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',
      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%2f53209532%2fhow-to-limit-input-from-user-to-numbers-and-letters-only-in-c%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      2
      down vote













      The simplest way you can achieve what you want is checking every character. As @Pete Becker pointed out, you may use isalnum to check if the character is a number or a letter character:



      #include <iostream>
      #include <string>

      int main () {
      std::string s = "Hello W>orld";

      for (auto c : s) {
      if (!isalnum(c)) {
      std::cout << "Found : '" << c << "'" << std::endl;
      }
      }

      return 0;
      }


      Output:



      Found : ' '
      Found : '>'





      share|improve this answer























      • Just for completeness, isalnum returns true when its argument is a letter or a number.
        – Pete Becker
        Nov 8 at 14:24










      • @PeteBecker Thanks for pointing out! Added that.
        – Ayxan
        Nov 8 at 14:30















      up vote
      2
      down vote













      The simplest way you can achieve what you want is checking every character. As @Pete Becker pointed out, you may use isalnum to check if the character is a number or a letter character:



      #include <iostream>
      #include <string>

      int main () {
      std::string s = "Hello W>orld";

      for (auto c : s) {
      if (!isalnum(c)) {
      std::cout << "Found : '" << c << "'" << std::endl;
      }
      }

      return 0;
      }


      Output:



      Found : ' '
      Found : '>'





      share|improve this answer























      • Just for completeness, isalnum returns true when its argument is a letter or a number.
        – Pete Becker
        Nov 8 at 14:24










      • @PeteBecker Thanks for pointing out! Added that.
        – Ayxan
        Nov 8 at 14:30













      up vote
      2
      down vote










      up vote
      2
      down vote









      The simplest way you can achieve what you want is checking every character. As @Pete Becker pointed out, you may use isalnum to check if the character is a number or a letter character:



      #include <iostream>
      #include <string>

      int main () {
      std::string s = "Hello W>orld";

      for (auto c : s) {
      if (!isalnum(c)) {
      std::cout << "Found : '" << c << "'" << std::endl;
      }
      }

      return 0;
      }


      Output:



      Found : ' '
      Found : '>'





      share|improve this answer














      The simplest way you can achieve what you want is checking every character. As @Pete Becker pointed out, you may use isalnum to check if the character is a number or a letter character:



      #include <iostream>
      #include <string>

      int main () {
      std::string s = "Hello W>orld";

      for (auto c : s) {
      if (!isalnum(c)) {
      std::cout << "Found : '" << c << "'" << std::endl;
      }
      }

      return 0;
      }


      Output:



      Found : ' '
      Found : '>'






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 8 at 14:39

























      answered Nov 8 at 14:22









      Ayxan

      1,06715




      1,06715












      • Just for completeness, isalnum returns true when its argument is a letter or a number.
        – Pete Becker
        Nov 8 at 14:24










      • @PeteBecker Thanks for pointing out! Added that.
        – Ayxan
        Nov 8 at 14:30


















      • Just for completeness, isalnum returns true when its argument is a letter or a number.
        – Pete Becker
        Nov 8 at 14:24










      • @PeteBecker Thanks for pointing out! Added that.
        – Ayxan
        Nov 8 at 14:30
















      Just for completeness, isalnum returns true when its argument is a letter or a number.
      – Pete Becker
      Nov 8 at 14:24




      Just for completeness, isalnum returns true when its argument is a letter or a number.
      – Pete Becker
      Nov 8 at 14:24












      @PeteBecker Thanks for pointing out! Added that.
      – Ayxan
      Nov 8 at 14:30




      @PeteBecker Thanks for pointing out! Added that.
      – Ayxan
      Nov 8 at 14:30












      up vote
      2
      down vote













      As @Someprogrammerdude mentioned in the comments, using std::all_of and an appropriate binary predicate(lambda function), you can do it easily as follows.



      Secondly, for checking the string input to its reverse string, just create a temporary string using the reverse iterators of std::string and check it. That way, you do not need to have another variable.



      Hope the comments will help you to understand more options.
      SEE LIVE



      #include <iostream>
      #include <cctype> // std::isdigit and std::isalpha and std::isalnum
      #include <string>
      #include <algorithm> // std::all_of

      int main()
      {
      std::string input; std::cin >> input;

      const auto check = (const char eachCar)->bool{ return std::isalnum(eachCar); };
      /* change return statement of lambda to
      std::isdigit(eachCar) ---> for only digits
      std::isalpha(eachCar) ---> for only letters
      */
      if(std::all_of(input.cbegin(), input.cend(), check))
      {
      if(input == std::string(input.crbegin(), input.crend()))
      std::cout << "It is a palindrome!";
      else std::cout << "No, it is not a palindrome!";
      }
      return 0;
      }


      Input:



      123kk321


      Output:



      It is a palindrome!





      share|improve this answer



























        up vote
        2
        down vote













        As @Someprogrammerdude mentioned in the comments, using std::all_of and an appropriate binary predicate(lambda function), you can do it easily as follows.



        Secondly, for checking the string input to its reverse string, just create a temporary string using the reverse iterators of std::string and check it. That way, you do not need to have another variable.



        Hope the comments will help you to understand more options.
        SEE LIVE



        #include <iostream>
        #include <cctype> // std::isdigit and std::isalpha and std::isalnum
        #include <string>
        #include <algorithm> // std::all_of

        int main()
        {
        std::string input; std::cin >> input;

        const auto check = (const char eachCar)->bool{ return std::isalnum(eachCar); };
        /* change return statement of lambda to
        std::isdigit(eachCar) ---> for only digits
        std::isalpha(eachCar) ---> for only letters
        */
        if(std::all_of(input.cbegin(), input.cend(), check))
        {
        if(input == std::string(input.crbegin(), input.crend()))
        std::cout << "It is a palindrome!";
        else std::cout << "No, it is not a palindrome!";
        }
        return 0;
        }


        Input:



        123kk321


        Output:



        It is a palindrome!





        share|improve this answer

























          up vote
          2
          down vote










          up vote
          2
          down vote









          As @Someprogrammerdude mentioned in the comments, using std::all_of and an appropriate binary predicate(lambda function), you can do it easily as follows.



          Secondly, for checking the string input to its reverse string, just create a temporary string using the reverse iterators of std::string and check it. That way, you do not need to have another variable.



          Hope the comments will help you to understand more options.
          SEE LIVE



          #include <iostream>
          #include <cctype> // std::isdigit and std::isalpha and std::isalnum
          #include <string>
          #include <algorithm> // std::all_of

          int main()
          {
          std::string input; std::cin >> input;

          const auto check = (const char eachCar)->bool{ return std::isalnum(eachCar); };
          /* change return statement of lambda to
          std::isdigit(eachCar) ---> for only digits
          std::isalpha(eachCar) ---> for only letters
          */
          if(std::all_of(input.cbegin(), input.cend(), check))
          {
          if(input == std::string(input.crbegin(), input.crend()))
          std::cout << "It is a palindrome!";
          else std::cout << "No, it is not a palindrome!";
          }
          return 0;
          }


          Input:



          123kk321


          Output:



          It is a palindrome!





          share|improve this answer














          As @Someprogrammerdude mentioned in the comments, using std::all_of and an appropriate binary predicate(lambda function), you can do it easily as follows.



          Secondly, for checking the string input to its reverse string, just create a temporary string using the reverse iterators of std::string and check it. That way, you do not need to have another variable.



          Hope the comments will help you to understand more options.
          SEE LIVE



          #include <iostream>
          #include <cctype> // std::isdigit and std::isalpha and std::isalnum
          #include <string>
          #include <algorithm> // std::all_of

          int main()
          {
          std::string input; std::cin >> input;

          const auto check = (const char eachCar)->bool{ return std::isalnum(eachCar); };
          /* change return statement of lambda to
          std::isdigit(eachCar) ---> for only digits
          std::isalpha(eachCar) ---> for only letters
          */
          if(std::all_of(input.cbegin(), input.cend(), check))
          {
          if(input == std::string(input.crbegin(), input.crend()))
          std::cout << "It is a palindrome!";
          else std::cout << "No, it is not a palindrome!";
          }
          return 0;
          }


          Input:



          123kk321


          Output:



          It is a palindrome!






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 8 at 14:51

























          answered Nov 8 at 14:45









          JeJo

          3,6143624




          3,6143624






















              up vote
              1
              down vote













              Assume the input has no space, you can do like this:



              char c; string s; bool chk = true;
              while (cin >> c)
              {
              if (('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
              s.push_back(c);
              else chk = false;
              }
              if (chk == true) cout << "Valid string";
              else cout << "Invalid string";


              The above code will terminate when there is no character left in the input.






              share|improve this answer

























                up vote
                1
                down vote













                Assume the input has no space, you can do like this:



                char c; string s; bool chk = true;
                while (cin >> c)
                {
                if (('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
                s.push_back(c);
                else chk = false;
                }
                if (chk == true) cout << "Valid string";
                else cout << "Invalid string";


                The above code will terminate when there is no character left in the input.






                share|improve this answer























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  Assume the input has no space, you can do like this:



                  char c; string s; bool chk = true;
                  while (cin >> c)
                  {
                  if (('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
                  s.push_back(c);
                  else chk = false;
                  }
                  if (chk == true) cout << "Valid string";
                  else cout << "Invalid string";


                  The above code will terminate when there is no character left in the input.






                  share|improve this answer












                  Assume the input has no space, you can do like this:



                  char c; string s; bool chk = true;
                  while (cin >> c)
                  {
                  if (('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
                  s.push_back(c);
                  else chk = false;
                  }
                  if (chk == true) cout << "Valid string";
                  else cout << "Invalid string";


                  The above code will terminate when there is no character left in the input.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 9 at 1:36









                  quanpham0805

                  349




                  349






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53209532%2fhow-to-limit-input-from-user-to-numbers-and-letters-only-in-c%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

                      how to define a CAPL function taking a sysvar argument

                      Schultheiß

                      Ansible :Unable to parse /etc/ansible/hosts as an inventory source