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

51,793 answers

573 users

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

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int is_valid_positive_integer(char str[]) {
    int isDigit = 1;
    int len = strlen(str);

    for (int i = 0; i < len; i++) {
        if (!isdigit(str[i])) {
            isDigit = 0;
            break;
        }
    }

    return isDigit;
}

int main() {
    char str[16] = "84390";

    if (is_valid_positive_integer(str)) {
        printf("Valid integer\n");
    }
    else {
        printf("Not a valid integer\n");
    }

    return 0;
}




/*
run:

Valid integer

*/

 



answered May 5, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
#include <ctype.h>
 
int is_valid_positive_integer(char str[]) {
    int isDigit = 1;
    int len = strlen(str);
    int i = 0;
    
    if (len == 0) return 0;

    if (str[0] == '+') {
        if (len == 1) {
            return 0; 
        }
        i = 1;
    }
 
    for (; i < len; i++) {
        if (!isdigit(str[i])) {
            isDigit = 0;
            break;
        }
    }
 
    return isDigit;
}
 
int main() {
    char str[16] = "84390";
    
    printf("%s\n", is_valid_positive_integer("84390") ? "yes" : "no");
    printf("%s\n", is_valid_positive_integer("+39") ? "yes" : "no");
    printf("%s\n", is_valid_positive_integer("-8") ? "yes" : "no");
    printf("%s\n", is_valid_positive_integer("13B") ? "yes" : "no");
 
}
 
 
 
 
/*
run:
 
yes
yes
no
no

 
*/

 



answered May 6, 2024 by avibootz

Related questions

1 answer 138 views
1 answer 99 views
1 answer 143 views
1 answer 94 views
3 answers 170 views
3 answers 114 views
...