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

1 Answer

0 votes
#include <iostream>
   
int main() {
    std::string str = "12";
       
    try {
         
        int n = stoi(str);
         
        std::cout << (n >= 0 ? "yes" : "no") << "\n";
      
        std::cout << (n >= 0) << "\n";
    } catch(...) {
        std::cout << "Not a number" << "\n";
    }  
}
 
 
   
   
/*
run:
   
yes
1
   
*/

 



answered Jun 25, 2022 by avibootz
edited Jun 25, 2022 by avibootz

Related questions

1 answer 275 views
2 answers 337 views
1 answer 199 views
3 answers 324 views
3 answers 284 views
1 answer 217 views
...