从文件c中读取multidigit int

时间:2014-06-11 06:47:22

标签: c getchar getc

所以我有一个名为num.txt的文本文件,它有一个由空格分隔的整数字符串。

所以让我们说num.txt包含:5 3 21 64 2 5 86 52 3

我想以读取格式打开文件并获取数字。所以我可以说

int iochar;
FILE *fp;

fp = fopen("num.txt", "r");
while ((iochar=getc(fp)) !=EOF){
    if(iochar!=' '){
        printf("iochar= %d\n", iochar); //this prints out the ascii of the character``
    }

^这适用于单位数字。但是我应该如何处理两位或三位或更多位的数字?

5 个答案:

答案 0 :(得分:4)

使用strtol()解析整数列表:

char buf[BUFSIZ];

while (fgets(buf, sizeof buf, stdin)) {
    char *p = buf;

    while (1) {
        char *end;

        errno = 0;
        int number = strtol(p, &end, 10);

        if (end == p || errno) {
            break;
        }

        p = end;

        printf("The number is: %d\n", number);
    }
}

如果要解析浮点数,请使用strtod()

答案 1 :(得分:2)

使用缓冲区存储读取字节,直到您点击分隔符,然后使用atoi解析字符串:

char simpleBuffer[12];    //max 10 int digits + 1 negative sign + 1 null char string....if you read more, then you probably don't    have an int there....
int  digitCount = 0;
int iochar;

int readNumber; //the number read from the file on each iteration
do {

    iochar=getc(fp);

    if(iochar!=' ' && iochar != EOF) {
        if(digitCount >= 11)
            return 0;   //handle this exception in some way

        simpleBuffer[digitCount++] = (char) iochar;
    }
    else if(digitCount > 0)
        simpleBuffer[digitCount] = 0; //append null char to end string format

        readNumber = atoi(simpleBuffer);    //convert from string to int
       //do whatever you want with the readNumber here...

       digitCount = 0;  //reset buffer to read new number
    }

} while(iochar != EOF);

答案 2 :(得分:1)

为什么不将数据读入缓冲区并使用sscanf来读取整数。

char nums[900];
if (fgets(nums, sizeof nums, fp)) {
    // Parse the nums into integer. Get the first integer.
    int n1, n2;
    sscanf(nums, "%d%d", &n1, &n2);
    // Now read multiple integers
}

答案 3 :(得分:0)

char ch;
FILE *fp;
fp = fopen("num.txt","r"); // read mode

if( fp != NULL ){
    while( ( ch = fgetc(fp) ) != EOF ){
        if(ch != ' ')
           printf("%c",ch);
    }
     fclose(fp);
}

答案 4 :(得分:0)

与OPs风格保持一致:
检测数字组并随时累积整数。

由于OP未指定整数类型且所有示例均为正数,因此假定类型为unsigned

#include <ctype.h>

void foo(void) {
  int iochar;
  FILE *fp;

  fp = fopen("num.txt", "r");
  iochar = getc(fp);
  while (1) {
    while (iochar == ' ')
      iochar = getc(fp);
    if (iochar == EOF)
      break;
    if (!isdigit(iochar))
      break;  // something other than digit or space
    unsigned sum = 0;
    do {

      /* Could add overflow protection here */

      sum *= 10;
      sum += iochar - '0';
      iochar = getc(fp);
    } while (isdigit(iochar));
    printf("iochar = %u\n", sum);
  }
  fclose(fp);
}