Skip to content

Instantly share code, notes, and snippets.

@andrija-zikovic
Created May 26, 2023 10:46
Show Gist options
  • Save andrija-zikovic/385927db4462ea4f7a7d47c645d4a681 to your computer and use it in GitHub Desktop.
Save andrija-zikovic/385927db4462ea4f7a7d47c645d4a681 to your computer and use it in GitHub Desktop.
CS50/atoi
#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