Chris
Chris

Reputation: 94

String parsing in C

how would you parse the string, 1234567 into individual numbers?

Upvotes: 2

Views: 440

Answers (3)

Delan Azabani
Delan Azabani

Reputation: 81384

char mystring[] = "1234567";

Each digit is going to be mystring[n] - '0'.

Upvotes: 9

What Delan said. Also, it's probably bad practice for maintainability to use a ASCII dependent trickery. Try using this one from the standard library:

int atoi ( const char * str );

EDIT: Much better idea (the one above has been pointed out to me as being a slow way to do it) Put a function like this in:

int ASCIIdigitToInt(char c){
    return (int) c - '0';
}

and iterate this along your string.

Upvotes: 3

Iain
Iain

Reputation: 984

Don't forget that a string in C is actually an array of type 'char'. You could walk through the array, and grab each individual character by array index and subtract from that character's ascii value the ascii value of '0' (which can be represented by '0').

Upvotes: 2

Related Questions