C++: Determining If a String Contains A Numeric Digit

  • Context: C/C++ 
  • Thread starter Thread starter ineedhelpnow
  • Start date Start date
  • Tags Tags
    Numeric String
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 7K views
ineedhelpnow
Messages
649
Reaction score
0
Set hadDigit to true if the 3-character passCode contains a digit.

Sample program:

Code:
#include 
#include 
#include 
using namespace std;

int main() {
   bool hasDigit = false;
   string passCode;
   int valid = 0;

   passCode = "abc";

   <student code>

   if (hasDigit) {
      cout << "Has a digit." << endl;
   }
   else {
      cout << "Has no digit." << endl;
   }

   return 0;
}

I'm super lost on this. I could definitely use some help/hints. Thanks
 
on Phys.org
One way to do this would be to use a "for" loop and check each character in the string sequentially to see if it is a digit or not. Once the first digit is detected, then hasDigit should be set to true and the loop should be broken, otherwise the loop will have checked all characters in the string and hasDigit will remain false.

For the "for" loop you will need the size of "passCode" as the value that the loop's index should be less than.

Also, it appears you need to include some libraries...
 
I can't say I am a fan of std::string in C++ as there are people who still insist on using char* or CString if you are using Microsoft stuff (and all the compatibility issues of these "string" classes).

However, if you are already using std:string, I would suggest you look at the reference of that library:

string - C++ Reference

It already provided handy functions like substr(), replace() and find_first_of() that answer a number of questions you posted fairly simply.