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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,989 questions

51,934 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
...