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!
            Asked
            
        
        
            Active
            
        
            Viewed 43 times
        
    -5
            
            
        - 
                    pleas share some code that you have tried and improve the question. – aaronR Mar 11 '18 at 18:34
 - 
                    Maybe this answer: https://stackoverflow.com/a/10829091/2785528 (check the others) might help – 2785528 Mar 11 '18 at 20:35
 
1 Answers
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
 - 
                    
 - 
                    
 - 
                    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