0

This is my code and I want to assign the string that I get from a file to a variable that I created as a struct.

#include <stdio.h>
#include <stdlib.h>

struct customer
{
    char customer_id[100];
    char service_type[100];
    char total_fee[100];
};

int main() 
{
    struct customer cust[100];
    int i;
    i = 0;
    char line[50];
    FILE* fptr;
    fptr = fopen("test.txt", "r");

    while (fgets(line, 50, fptr))
    {
        line = cust[i].customer_id; ///String is not modifiable  so this solution cannot be applied
    }
}

Any solution to this problem?

Lorale
  • 113
  • 6
  • 2
    use `strcpy` function. – kiran Biradar May 17 '20 at 12:47
  • 1
    Use `strcpy`: `strcpy(line, cust[i].customer_id);`. Also be mindful of the fact that `customer_id` may be longer than `line` size. So either ensure buffer size is sufficient or use `snprintf` and such to take of care buffer overflows. – P.P May 17 '20 at 12:49
  • 1
    Off topic: but your struct is considering arrays of 100 items as well as the definition of `customer cust[100]` is also 100. You may not need to define the members of the struct to be arrays of 100 items because that is done when you declared the `customer cust[100]`. – campescassiano May 17 '20 at 12:55
  • 2
    Off topic: you are not incrementing the `i` in your `while` loop. So, remember to increment that. – campescassiano May 17 '20 at 12:56

0 Answers0