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.
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
.
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.
当您使用 fscanf 将输入读入 char 数组时,您可以遍历该数组并将 atoi 应用于每个元素并将输出(整数)放入 int 数组中。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.