Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,166 questions

40,722 answers

573 users

How to determine if a string is numeric in C++

2 Answers

0 votes
#include <iostream>
#include <string>
 
bool isNumeric(std::string const &str) {
    auto it = str.begin();
    
    if (*it == '-') it++;
    
    while (it != str.end() && std::isdigit(*it)) {
        it++;
    }
    return !str.empty() && it == str.end();
}
 
int main() {
    std::string str = "1284";
 
    std::cout << std::boolalpha << isNumeric(str) << "\n";
    
    std::cout << std::boolalpha << isNumeric("-3") << "\n";
}




/*
run:

true
true

*/

 





answered Jun 26, 2022 by avibootz
0 votes
#include <iostream>
#include <string>
 
bool isNumeric(std::string const &str) {
    char* p;
    
    strtol(str.c_str(), &p, 10);
    
    return *p == 0;
}
 
int main() {
    std::string str = "1284";
 
    std::cout << std::boolalpha << isNumeric(str) << "\n";
    
    std::cout << std::boolalpha << isNumeric("-3") << "\n";
}





/*
run:

true
true

*/

 





answered Jun 26, 2022 by avibootz
...