Code Issues Solver | C/C++

CSV Parser for Numerical Arrays in C

This C code parses a CSV formatted string, converts the numerical values to an array of doubles, and addresses common pitfalls in string handling and parsing logic for improved functionality.


Empty image or helper icon

Prompt

#include 
#include 
#include

int get_data_csv(double ar[], int max_length, char * ptr){
    int number = 0;
    while (*ptr != NULL){
        ptr = strchr(ptr, ' ');
        ptr ++;
        float temp = atof(*ptr);
        
        ar[number] = temp;
        number++;
        ptr ++;
        
       
    }
    return number;
}
    

int main(void)
{
    char str[100] = {"csv: 0.56; -65.43; 0.1; 11.0\0"};
    double final[100];
    get_data_csv(final, 20, &str);
  
    
    
    // здесь продолжайте функцию main

    return 0;
}

Answer

Problem Analysis

The provided C code is intended to parse a CSV formatted string and convert numerical values into an array of doubles. However, there are several issues:

  1. The string parsing logic does not correctly handle the input format.
  2. Incorrect usage of the atof function.
  3. Infinite loop potential due to improper termination condition in the while loop.

Review of Previous Attempts

The original attempt:

  1. Improper handling of the NULL condition in the while loop.
  2. Misuse of the atof function by passing a dereferenced pointer.
  3. Incorrect parsing logic around the delimiters.

Proposed Solution

To correct these issues and properly parse the input CSV:

  1. Use strtok for tokenizing the input string based on delimiters.
  2. Properly convert each token into a double using atof.
  3. Ensure safe access to the ar array by checking max_length.

Updated Code

#include 
#include 
#include 

// Function to parse the CSV and populate the array with numbers.
int get_data_csv(double ar[], int max_length, char *ptr) {
    int number = 0;
    char *token;
    
    // Skip the initial "csv: " part
    ptr = strchr(ptr, ' ') + 1;
    
    token = strtok(ptr, ";");
    while (token != NULL && number < max_length) {
        ar[number++] = atof(token);
        token = strtok(NULL, ";");
    }
    
    return number;
}

int main(void) {
    // CSV string initially provided
    char str[100] = "csv: 0.56; -65.43; 0.1; 11.0";
    double final[100];
    
    // Call the CSV parser function
    int count = get_data_csv(final, 20, str);
  
    // Print the results for verification
    for(int i = 0; i < count; i++) {
        printf("final[%d] = %lf\n", i, final[i]);
    }
    
    return 0;
}

Code Explanation

  1. Imports:

    • Standard input/output and string libraries for basic operations.
    • Standard library for atof conversion.
  2. Function get_data_csv:

    • The ptr pointer is advanced to skip the initial "csv: " portion.
    • Tokenization is achieved using strtok with a semicolon (;) as the delimiter.
    • Each token is converted to a double using atof and stored in the ar array.
    • The number counter keeps track of the array index and ensures we do not exceed max_length.
  3. Main Function:

    • Initializes the input string and calls get_data_csv.
    • The count of parsed numbers is used to iterate through the array and print each value for verification.

Code Usage Example

To use this code in a real-world scenario:

  1. Modify the input string to represent different CSV formatted data.
  2. Adjust the max_length parameter to fit the expected data size.
  3. Use the get_data_csv function to convert CSV strings directly into numerical arrays for further processing in statistical analysis or other applications.

Final Note

This solution ensures proper handling of input parsing, avoiding common pitfalls with pointer management and string tokenization in C. For further learning, consider exploring the Enterprise DNA Platform for courses on advanced data handling techniques.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This C code parses a CSV formatted string, converts the numerical values to an array of doubles, and addresses common pitfalls in string handling and parsing logic for improved functionality.