Convert ascii to int

gcc 4.5.1 c89

I have a buffer filled with char characters. I need to compare them:

This is an example of the contents of a buffer:

vote buffer [ 51 ] vote buffer [ 32 ] vote buffer [ 49 ] vote buffer [ 32 ] vote buffer [ 50 ] vote buffer [ 32 ] vote buffer [ 53 ] vote buffer [ 32 ] 

I am trying to get the int-equivalent of these char, which are in the buffer for comparison.

 #define NUMBER_OF_CANDIDATES 7 if((vote_data.vote_buff[i] > NUMBER_OF_CANDIDATES || vote_data.vote_buff[i] < 1) { /* Do something */ } 

As you can see, this will never be true in the if statement, since the range is much larger.

I tried casting (int). However, this did not solve the problem.

I think I could calculate ascii from the character set. However, I would prefer not to add more complexity if I cannot help.

Thanks so much for any advice,

+4
source share
3 answers

If you just want to convert individual characters to int , you can use c - '0' (which is equivalent to c - 48 ). If you want to convert strings of more than one character, use sscanf()

+3
source

You can use atoi to convert strings as integers. Char and int are the same in C

 int main (int argc, char** argv) { int n=65; char* String; String="1234"; printf("String: %s - Integer: %d\n", String, atoi(String)); printf("int %d is char: %c\n ", n, n); } 
+5
source

There is nothing in the standard library to turn char into int . This is because most int do not fit into char . However, there are several ways to turn a string into an int , because it is much more often done. You can easily use them by copying each char into the first element of an array of length 2 with the second char 0 and using this as input for atoi() , sscanf() or strtol() . (I would recommend one of the last two in a real program, as they allow you to check for errors.)

 char buffer[2] = {0,0}; int i; for (i = 0; i < vote_count; ++i) { int vote; buffer[0] = vote_data.vote_buff[i]; vote = atoi(buffer); /* handle vote */ } 

Using ASCII values ​​and subtracting '0' is certainly a workable option. Any reasonable character set will have numbers in order.

It would be best to change the interface so that your routine does not receive a char array, but an int array. The external interfaces of the program should be responsible for the disinfection of the input data and turning them into something easy to process. Currently, there is no way to easily change the program to support more than ten candidates. Providing input int storage procedures eliminates this.

+2
source

All Articles