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 279 views
2 answers 343 views
1 answer 203 views
3 answers 331 views
3 answers 290 views
1 answer 221 views
...