Hi,

there is that thing that i need to handle atoi () function error.. Now for explanation atoi ( some const char * which is int (like '1') ) gives me that int, but if i write like this atoi ( 'n' ) then shit happens and it return's a 0.
So in order to do something when wrong happens i logicaly would do so:

if ( atoi ( (const char *) some_char ) == 0 )
{
/*<...>
things i want to do
<...>*/
}

but my linux console say's segmentation fault after i run my compiled program with that kind of thing.

So how can i control that error, so i could do things i want when things go bad ? or i should use another conversion from char to int (but that conversion would have to say when things are bad) ?

What is 'some_char'?

What is 'some_char'?

simply some char, like:

char some_char = 'n' ;

Right from my help files.

int atoi(const char *nptr);

The atoi() function converts the initial portion of the string pointed
to by nptr to int.

atoi accepts a c-string not a char.

you should probably use isdigit() instead, to decide if doing atoi() is worthwhile. More about these kinds of things here

Right from my help files.

int atoi(const char *nptr);

The atoi() function converts the initial portion of the string pointed
to by nptr to int.

atoi accepts a c-string not a char.

ok, then how can i make char into c-string ? just for the future, and curiosity, because the post above is wonderful, didn't knew about those functions.

you should probably use isdigit() instead, to decide if doing atoi() is worthwhile. More about these kinds of things here

thank's ;) you are wonderful, i will use it, but i am still waiting for the answer about the char..

thank's ;) you are wonderful, i will use it, but i am still waiting for the answer about the char..

I don't know the details of about how atoi() works, but I expect that it looks for a \0 character, and a simple char doesn't have that. This would mean that atoi() would just keep going through memory until it happens to come across a \0 . So,

char num = '1';
atoi(num);

will fail to compile, but

char num[] = "1";
atoi(num);

will work fine, since the string is null-terminated. Just casting a char to a const char * does not give you the null terminating character.

What's the wider context of what you're trying to do, maybe there's an alternative way?

ravenous beat me to the answer.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, const char **argv)
{
	char ch[] = "12";

	int ans = atoi(ch);

	fprintf(stdout, "ans->%d\n", ans);
	return 0;
}

Thank you guys ;)

to convert a chat to int you only need to do this:

char character = '1';
int number = character - '0'; //now number equals 1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.