Created
May 26, 2023 10:46
-
-
Save andrija-zikovic/385927db4462ea4f7a7d47c645d4a681 to your computer and use it in GitHub Desktop.
CS50/atoi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cs50.h> | |
#include <ctype.h> | |
#include <math.h> | |
#include <stdio.h> | |
#include <string.h> | |
int convert(string input); | |
int main(void) | |
{ | |
string input = get_string("Enter a positive integer: "); | |
for (int i = 0, n = strlen(input); i < n; i++) | |
{ | |
if (!isdigit(input[i])) | |
{ | |
printf("Invalid Input!\n"); | |
return 1; | |
} | |
} | |
// Convert string to int | |
printf("%i\n", convert(input)); | |
} | |
int convert(string input) | |
{ | |
// TODO | |
int num = 0; | |
for (int i = 0; i < strlen(input); i++) | |
{ | |
while (input[i] && (input[i] >= '0' && input[i] <= '9')) | |
{ | |
num = num * 10 + (input[i] - '0'); | |
i++; | |
} | |
} | |
return num; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment