0

我有如下文件:

1 2 300 500 5 117 5 90 45 34 ---- -------------- 34566

7 8 16 8 39 167 80 90 38 4555

等等我怎样才能得到每个数字并存储一个二维数组?

到目前为止,我可以使用 fgets() 函数读取该行。

FILE *fp = NULL;
char buffer[1024];
 fp = fopen("Input.txt","r"); 
if(fp!=NULL)
{
  while(fgets(buffer,1024,fp)!=NULL)
  {
    // i need help here

   } 
 }

是否有另一种解决方法(比这更好)而不是使用 fgets()?

4

3 回答 3

1

它可能是这样的:

int i = 0;
int num[20];
while (buffer[i] != '\0')
{
  int j = 0;
  char a[80];
  while (buffer[i] != ' ')
  {
    a[j] = buffer[i];
    ++j;
    ++i;
  }
  if (buffer[i] == '\0')
    break;
  a[j] = '\0';
  const char* b = &a[0];
  num[i] = strtol(b, NULL, 10);
  ++i;
}

...虽然内存管理在这里很脏。必须努力。

于 2013-07-23T07:30:43.533 回答
1
#include <stdio.h>
#include <stdlib.h>

int main(void){
    //Either the two-pass or ensure dynamically allocate and expand by `realloc` if size of the array can't be determined in advance, 

    static int array[20][20];
    int row=0;
    FILE *fp = NULL;
    char buffer[1024];
    fp = fopen("Input.txt","r"); 
    if(fp!=NULL) {
        while(fgets(buffer,1024,fp)!=NULL){
            char *p = buffer, *endp;
            long num;
            int col = 0;
            do{
                num = strtol(p, &endp, 10);
                if(*endp == ' ' || *endp == '\n' || *endp == '\0'){
                    array[row][col++] = num;
                }
                p = endp + 1;
            }while(*endp != '\n' && *endp != '\0');
            ++row;
        }
        fclose(fp);
    }
    return 0;
}
于 2013-07-23T09:15:01.687 回答
0

工作代码:

#include <stdio.h>
#include <string.h>

int main()
{
    char *str_avail;
    char *token;
    FILE *fp = NULL;
    char buffer[1024];
    char buffer2[1024];

    fp = fopen("test.txt","r"); 
    if(fp!=NULL)
    {
        while(fgets(buffer,1024,fp)!=NULL)
        {
            printf("%s\n", buffer);
            str_avail = strpbrk(buffer, ":");
            if(*buffer == '\n')
                continue;
            strcpy(buffer2, str_avail+2);
            token = strtok(buffer2, " ");
            while(token != NULL){
                    printf("%s\n", token);
                        token = strtok (NULL, " ");
            }
        } 
    }
}
于 2013-07-23T07:36:18.633 回答