开发者

Load numbers from text file in C [closed]

开发者 https://www.devze.com 2022-12-10 19:26 出处:网络
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist

Closed 9 years ago.

Improve this question

I'm wanting to load a known number of numbers into an array in C from a text file (.txt). The format would be:

开发者_高级运维"0,1,2,5,4"

I'm kinda new to C, can anyone recommend a way to load in the text file?

Cheers


It can be done easily with fscanf:

#include <stdio.h>
int main()
{
    FILE* f = fopen("test.txt", "r");
    int number = 0;
    int sum = 0; /* the sum of numbers in the file */

    while( fscanf(f, "%d,", &number) > 0 ) // parse %d followed by ','
    {
        sum += number; // instead of sum you could put your numbers in an array
    }

    fclose(f);
}

@pmg: Sure, why not. I just though if it is a hw, then it is a bad thing to give a complete solution :)

#include <stdio.h>
int main()
{
    FILE* f = fopen("test.txt", "r");
    int n = 0, i = 0;
    int numbers[5]; // assuming there are only 5 numbers in the file

    while( fscanf(f, "%d,", &n) > 0 ) // parse %d followed by ','
    {
        numbers[i++] = n;
    }

    fclose(f);
}


You can:

1) Read one number at a time and convert to int using atoi()

2) You can read the whole array at once and using strtok to divide the number and after that convert with atoi()

Here there is an example of strtok:

  int main(int argc, char *argv[])
{
        int x = 1;
        char str[]="this:is:a:test:of:string:tokenizing";
        char *str1;

        /* print what we have so far */
        printf("String: %s\n", str);

        /* extract first string from string sequence */
        str1 = strtok(str, ":");

        /* print first string after tokenized */
        printf("%i: %s\n", x, str1);

        /* loop until finishied */
        while (1)
        {
                /* extract string from string sequence */
                str1 = strtok(NULL, ":");

                /* check if there is nothing else to extract */
                if (str1 == NULL)
                {
                        printf("Tokenizing complete\n");
                        exit(0);
                }

                /* print string after tokenized */
                printf("%i: %s\n", x, str1);
                x++;
        }

        return 0;


Hy try this.

#include <stdio.h>
#define MAX_NUMBERS   1000    /* Max numbers in file */
const char DATA_FILE[] = "numbers.dat";  /* File with numbers */

int data[MAX_NUMBERS];  /* Array of numbers  */

int main()
{
    FILE *in_file;  /* Input file */
    int  middle;    /* Middle of our search range */
    int low, high;  /* Upper/lower bound */
    int search;    /* number to search for */
    char line[80];  /* Input line */

    in_file = fopen(DATA_FILE, "r");
    if (in_file == NULL) {
  fprintf(stderr,"Error:Unable to open %s\n", DATA_FILE);
  exit (8);
    }

    /*
     * Read in data 
     */

    max_count = 0;
    while (1) {
  if (fgets(line, sizeof(line),  in_file) == NULL)
      break;

  /* convert number */
  sscanf(line, "%d", &data[max_count]);
  ++max_count;
    return data;
   }
   return (0);
}


Always make sure what you are reading from the value. If you are reading characters from the file ok. But if you want to read integers always make sure you read them as characters and convert them to integers.

#include<stdio.h>
int main()
{
    char a;
    FILE *point;
    int i, b[4];
    point = fopen("test.txt", "r");
    for(i = 0; i < 4; i++) {
            a = fgetc( point); 
        b[i] = atoi(&a);              
    }
    fclose(point);
// printing put the values ,but i dont get the text file values
    for(i = 0; i < 4; i++) 
        printf("%d\n" , b[i]);  
}

this is my text file,

3210

this is my output,

3
2
1
0
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号