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 に答える
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

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 に答える
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 に答える