• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C++ The first element when reading CSV in C

kenny0541

New Coder
I am trying to read data looks like this in a CSV file

My data:
apple,4.2
banana,3.2
orange,5
limon,2

My code is like this, the file can be opened. However, and all the data can be stored in input in s1, and s2. Next, use strcmp to compare s1 with items in app array. If s1 is the same as the element ordered in app array, s2 will be store into S[i]. The others rows in my data work fine, except the first one, apple, even though, the two are the same when I print them out. Can anyone suggest what went wrong?

the output:
s1 is apple.
value is 4.2.
App is apple.
Wrong parameter format for apple.
actual code:
void read_parameter(char* path)
{
    FILE *fp_parameter;
    char s1[nameLen];
    char s2[nameLen];
    int i = 0;
    double S[4];
    char *app[] = {"apple", "banana", "orange", "limon"};
    fp_parameter = fopen(path, "r");
   
    if (!fp_parameter)
    {
        printf("Parameter file cannot open...\n");
        exit(1);
    }
    else
    {
        printf("Parameter file opening...\n");

        while (EOF != fscanf(fp_parameter, "%20[^','],%s ", s1, s2))
        {
            printf("s1 is %s.\n", s1);
            printf("value is %s.\n", s2);
            printf("App is %s.\n", *(app+i));
           
            if (strcmp(s1, *(app+i)) == 0)
            {
                S[i] = atof(s2);
                printf("Space limitation for %s is %f\n", *(app+i), S[i]);
                i++;
            }
            else
            {
                printf("Wrong parameter format for %s.\n\n", *(app+i));
                i++;
            }
        }
        fclose(fp_parameter);
    }
    printf("\n");}
}
 

Top