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,868 questions

51,791 answers

573 users

How to check if a string is a valid positive or negative integer in C++

1 Answer

0 votes
#include <iostream>

bool is_valid_positive_or_negative_integer(const std::string& s) {
    if (s.empty()) return false;

    size_t start = 0;
    if (s[0] == '-' || s[0] == '+') {
        if (s.size() == 1) return false; 
        start = 1;
    }

    for (size_t i = start; i < s.size(); ++i) {
        if (!std::isdigit(s[i])) {
            return false;
        }
    }

    return true;
}

int main() {
    
    std::cout << (is_valid_positive_or_negative_integer("123") ? "yes" : "no") << "\n";
    std::cout << (is_valid_positive_or_negative_integer("+8492") ? "yes" : "no") << "\n";
    std::cout << (is_valid_positive_or_negative_integer("-300") ? "yes" : "no") << "\n";
    std::cout << (is_valid_positive_or_negative_integer("12W") ? "yes" : "no") << "\n";
}



/*
run:

yes
yes
yes
no

*/

 



answered May 6, 2024 by avibootz

Related questions

...