将一组字符转换为文件中的int

时间:2010-11-07 14:25:42

标签: c input integer char

我在读:

22:5412:99:00 (...)

使用(ch=fgetc(fp)) != EOF的文本文件,因为我没有只读取这些数字。 使用if(ch >= 48 && ch <= 57)很容易识别一个数字,但问题是我想将这些数字22,5412放入一个整数数组中。但是,当我读取一个字符时,它会读取部分数字,因为每个数字都是char。 它得到2(而不是我想要的22)并且在下一次迭代中读取另外的2.如何将每组数字保存到它自己的整数中?

我希望我很清楚,谢谢!

4 个答案:

答案 0 :(得分:0)

您需要将数字存储为字符串或char *,并使用atoi将其实际转换为数字。 http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

答案 1 :(得分:0)

我的想法是在每个char中读取,如果是数字,则将其附加到缓冲区。每当我们得到一个非数字时,我们只需使用sscanf将缓冲区的内容作为字符串读取,并清除缓冲区以获取下一个值。

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

int read_buffer(char* buffer, int* sz)
{
    int ret;
    if (*sz==0) return 0;
    buffer[*sz]='\0'; //end the string
    sscanf(buffer,"%d", &ret); //read the contents into an int
    *sz=0; // clear the buffer
    return ret;
}

int main()
{
    char buffer[1000];
    int sz=0;
    char ch;
    FILE* input=fopen("input.txt","r");
    // "input.txt" contains 22:5412:99:00
    while ((ch=fgetc(input))!=EOF)
    {
        int number;
        if (isdigit(ch))
        {
            buffer[sz++]=ch; // append to buffer
        }
        else
        {
            printf("Got %d\n",read_buffer(buffer,&sz)); // read contents of buffer and clear it
        }
    }
    if (sz) // check if EOF occured while we were reading a number
        printf("Got %d\n",read_buffer(buffer,&sz)); 
    fclose(input);
    return 0;
}

答案 2 :(得分:0)

假设您的模式是NN:NNNN:NN:NN类型,解析分隔符,将字符输入缓冲区:

int idx = 0, nIdx = 1;
int firstN, secondN, thirdN, fourthN;
char buf[5];
...
while ((ch=fgetc(fp)) != EOF) {
    if (ch != ':') {
        buf[idx++] = ch;
    } 
    else {
        buf[idx] = '\0';
        idx = 0;
        switch (nIdx++): {
            case 1: firstN = atoi(buf); break;
            case 2: secondN = atoi(buf); break;
            case 3: thirdN = atoi(buf); break;
        }
    }
}
buf[idx] = '\0';
fourthN = atoi(buf);
...

答案 3 :(得分:0)

我做了上一篇文章的完整程序 - 并进行了一些测试: - )

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

/* fill `array` with at most `siz` values read from the stream `fp` */
/* return the number of elements read */
size_t fillarray(int *array, size_t siz, FILE *fp) {
  int ch;
  size_t curr = 0;
  int advance_index = 0;
  while ((ch = fgetc(fp)) != EOF) {
    if (isdigit((unsigned char)ch)) {
      array[curr] *= 10;
      array[curr] += ch - '0';
      advance_index = 1;
    } else {
      if (advance_index) {
        advance_index = 0;
        curr++;
        if (curr == siz) { /* array is full */
          break;
        }
      }
    }
  }
  return curr + advance_index;
}

int main(void) {
  int array[1000] = {0};
  int n, k;

  n = fillarray(array, 1000, stdin);
  if (n > 0) {
    printf("%d values read:\n", n);
    for (k=0; k<n; k++) {
      printf(" %d", array[k]);
    }
    puts("");
  } else {
    fprintf(stderr, "no data read\n");
  }
  return 0;
}

试运行

$ ./a.out 
24555:76423 foobar 76235 jgfs(8) jhg x86-64 passw0rd RS232
[CTRL+D]
8 values read:
 24555 76423 76235 8 86 64 0 232