0

I have a file with a number like "100000". Is there a way to store each digit in an array? For example, I make an array[100] and I want array[0] = 1, array[1] = 0, array[2] = 0 and etc. I've looked it up but from what I gather, if I use a char array it takes it as a whole.

3 Answers 3

3

I probably would not use fscanf() for this:

while ((c = fgetc(fp)) != EOF && isdigit(c)) array[i++] = c - '0'; 

If you must use fscanf(), then:

int i = 0; int v; while (fscanf(fp, "%1d", &v) == 1) { assert(v >= 0 && v <= 9); array[i++] = v; } 

The 1 in the format string limits the integer to one digit. You must pass in an int * if you use %1d. If you have C99 support in your library, you could use:

int i = 0; while (fscanf(fp, "%1hhd", &array[i++]) == 1) ; 

The hh length modifier indicates that the pointer is a pointer to char (very short integer) rather than a pointer to int.

Sign up to request clarification or add additional context in comments.

5 Comments

In the first example, why do you substract '0' ?
@Amit: because the character code for '0' is typically 48 (but that is not guaranteed), and the character code for '9' is typically 57, so to convert from the character code for a digit to the number corresponding to the digit, you subtract '0'. This works for every codeset (EBCDIC, ISO/IEC 8859-x, Unicode, etc). It only runs into problems if there are other types of digits, such as the Hindi digits (Unicode U+0660 ARABIC-INDIC DIGIT ZERO, etc).
I'm sorry but I'm still confused. You're storing a character that you read into the char variable c, correct? So you read the digit 1, store it as a character into c, and then store c - 0 into the integer array. Would you substract 0 for any integer that is read. For example, what if the file had 14122. Would this approach still work?
@Amit: printf("%c %d\n", '0', '0'); will most likely print 0 48. So, reading one character into a variable c, if the character is '0' (note the single quotes), the value stored is (probably) 48. To convert that to 0 (note the absence of quotes), we can subtract '0'; the same subtraction from '1' will yield 1, and from '2' will yield 2, etc. So, each digit read will be converted into a number. When treated as a character, 0 could be regarded as control-@, and 1 as control-A, and 2 as control-B, etc, or 0 as NUL, 1 as SOH, 2 as STX, etc. Note that '0' != 0; that is crucial.
+1 @Jonathan Leffler: I understand now, thanks a lot, that clarifies things. Still a C noob :/
0

Is the number stored as literal '100000', or as its binary representation? if it's the literal '100000', just read it into a string, which is a char array already.

Comments

0

As you use fscanf to read input into a char array, you can iterate over that array and apply atoi to each element and put the output (an integer) into your int array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.