ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Is there a function, accessible in a common library, to convert from a string (of numbers) into an integer?
I mean an string library string, not an array of char's (so atoi is not an option)
I can do it manually, but that is kinda hacky as im sure i dont do proper error checking
I am just trying to find somethig universal and simple so i can go:
#include<magiclibrary>
int i;
string s = "123";
i = magicFunction(s);
Does such a creature exist in a librarry common to all compliers?
well you could write your own code to do that too i guess
maybe something like
Code:
//atoi.c
#include<stdio.h>
int main(){
char st[]="123";
int i=0;
for(;i<(int)strlen(st)+1;i++)
printf("%d ",st[i]); //you could replace %d with whatever you want
printf("\n");
return 0;
}
that code should do it it'll convert any character into a number giving you it's ascii value
What about this one I made? I'm still kind of newbie and learning so I hope it's not too long or buggy.
Code:
/*
This function converts a string to an int.
If the string contains not only numbers, but other
signs (including "+" or "-"), the function will
return 0.
*/
#include <stdio.h>
#include <string.h>
int string_to_int (char s[4])
{
int n, i;
n = 0;
i = 0;
while (i < strlen (s))
{
if (s[i] == 48)
n = n * 10 + 0;
if (s[i] == 49)
n = n * 10 + 1;
if (s[i] == 50)
n = n * 10 + 2;
if (s[i] == 51)
n = n * 10 + 3;
if (s[i] == 52)
n = n * 10 + 4;
if (s[i] == 53)
n = n * 10 + 5;
if (s[i] == 54)
n = n * 10 + 6;
if (s[i] == 55)
n = n * 10 + 7;
if (s[i] == 56)
n = n * 10 + 8;
if (s[i] == 57)
n = n * 10 + 9;
i = i + 1;
}
return n;
}
main ()
{
char s[4];
strcpy (s, "1453");
printf ("The string is %s\n", s);
printf ("The number is %i\n", string_to_int (s));
}
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.