-5

I'm need to create id just number. For example: 12345678 If user inputs fail( contain char), delete char immediately. For example: 123a =>input gain! Please help me!

1 Answers1

0

I think this is what you are looking for:

#include <iostream>
#include <string>
#include <cctype>

int main () {
  std::string input;
  bool valid;
  do {
    valid = true;
    std::cin >> input;
    for (char c : input)
      if (! std::isdigit( static_cast<unsigned char>(c) ) )
        valid = false;
  } while (! valid);
  // Here the string is guaranteed to be valid
}

Be aware though, that whatever you are trying to do, this does not look like the proper way to do it. There are ways to read numbers in c++, and this is not what I would recommend.

Robindar
  • 484
  • 2
  • 9
  • You should cast the argument of `std::isdigit` to `unsigned char`, see http://en.cppreference.com/w/cpp/string/byte/isdigit. – Christian Hackl Mar 11 '18 at 19:49
  • char c : input ??? Please explain. – Đặng Quốc Cường Mar 12 '18 at 04:10
  • @ChristianHackl You're right, sorry I missed that – Robindar Mar 12 '18 at 13:49
  • This is a range-based for loop. See [C++ Reference: Range-for](http://en.cppreference.com/w/cpp/language/range-for). This will iterate over the characters of the string input – Robindar Mar 12 '18 at 13:52
  • @Sevis: Your edit made it worse. You still do not cast the argument to `unsigned char`, which would be necessary to prevent UB, but the *result*, which is wrong. Even worse, it's a C-style cast. The whole line should go like this instead: `if (!std::isdigit(static_cast(c)))` – Christian Hackl Mar 13 '18 at 06:27