-->

读多位从文件c诠释(read multidigit int from file c)

2019-10-20 06:30发布

所以我有一个名为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``
    }

^这适用于单个数字。 但我应该怎么有两个或三个或多个数字处理的数字?

Answer 1:

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()



Answer 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);


Answer 3:

你为什么不将数据读入缓冲区,并使用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
}


Answer 4:

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);
}


Answer 5:

在使用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);
}


文章来源: read multidigit int from file c
标签: c getchar getc