1

So I have a text file called num.txt that has a string of integers separated by a space.

So let's say num.txt contains: 5 3 21 64 2 5 86 52 3

I want to open the file in read format and get the numbers. So I can say

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``
    }

^this works for single-digit numbers. but how should I handle numbers with two or three or more digits?

4

5 回答 5

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

于 2014-06-11T06:53:19.833 回答
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);
于 2014-06-11T07:03:53.860 回答
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
}
于 2014-06-11T06:54:17.230 回答
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);
}
于 2014-06-11T07:00:19.920 回答
0

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

由于 OP 没有指定整数的类型并且所有示例都是正数,因此假设 type 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);
}
于 2014-06-11T12:04:54.363 回答