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

发布于 2024-10-01 04:40:17 字数 331 浏览 6 评论 0原文

我正在阅读:

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

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

我希望我说得足够清楚,谢谢!

I'm reading:

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

From a text file using (ch=fgetc(fp)) != EOF because I don't have only those numbers to read.
Identifying a number is easy with if(ch >= 48 && ch <= 57) but the thing is I want to put those numbers 22, 5412 into an array of integers. However when I read a char it reads part of number since each number is char.
It gets 2 (and not 22 like I want to) and in the next iteration reads the other 2. How can I save each set of numbers into it's own integer?

I hope I was clear enough, thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风蛊 2024-10-08 04:40:17

我的想法是读取每个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;
}

My idea is to read in each char, and if it is a digit append it to a buffer. Whenever we get a non-digit, we just read the contents of the buffer as a string using sscanf, and clear the buffer for the next value.

#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;
}
像你 2024-10-08 04:40:17

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

You would need to store the numbers as a string or a char* and use atoi to actually convert it to a number. http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

却一份温柔 2024-10-08 04:40:17

假设您的模式是 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);
...

Assuming your pattern is of the type NN:NNNN:NN:NN, parse on the delimiter, feeding characters into a buffer:

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);
...
纵情客 2024-10-08 04:40:17

我在上一篇文章中做了一个完整的程序——以及一些测试:-​​)

#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

I did a full program out of the previous post -- and some testing :-)

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

And a test run

$ ./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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文