Question

In: Computer Science

Write a program that reads in a continuous stream of strings representing a line of CSV...

Write a program that reads in a continuous stream of strings representing a line of CSV data in the format "NAME,AGE,EMAIL,DOB". Implement a function check_csv which verifies that each input string matches this format by ensuring that: • There are 4 tokens in the string corresponding to the 4 properties above. • The second token MUST be a number. • The fourth token should be in the format MM-DD-YYYY (hint: tokenize this as well). The function should return 0 if the CSV string is valid, and 1 otherwise. Your program should read CSV strings until the string "END" is entered as input. Print all valid strings to stdout followed by a line indicating how many invalid strings were entered. • You can use a character array with a buffer size of 1024 for reading each line using fgets. • You may not use any library specifically for parsing CSV. • Save your code as prob5.c.

Solutions

Expert Solution

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int isleap(int year) //return 1 if leap year
{
  return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
}
int isvaliddate(int d,int m,int y) //return 1 if date is valid
{
  int month[12]={31,28,31,30,31,30,31,31,30,31,30,31};
  if(isleap(y))
    month[1]=29;
  if(y>=1900 && y<=9999)//check year
  {
    if(m>=1 && m<=12) //check month
    {
      if(d>=1 && d<= month[m-1])
        return 1;
      else
        return 0;
    }
    else
      return 0;
  }
  else 
    return 0;
}
int check_csv(char *data)
{
  int isvalid=0; // let string is valid
  char dummy[100]; // dummy string to copy data
  strcpy(dummy,data); // strcpy to copy a string to other
  char* token = strtok(dummy,","); // tokenizing string
  char *attr[4]; // to store 4 tokens
  int i=0; 
  while (token != NULL)
  { 
    attr[i++]=token; //assign token in array
    token = strtok(NULL,","); //further token the string
  }
  //checking if attr[1] is number or not
  int count=0,flag=0;
  for(int i=0;i<strlen(attr[1]);i++)
  {
    if(isdigit(attr[1][i]))
      count++;
    if(attr[1][i]=='.')//for a float
    {
      flag=1;
    }
  }
  if(flag==0 && count==strlen(attr[1])) //valid case
    ;
  else if(flag==1 && count==strlen(attr[1])-1)
    ;
  else
    isvalid=1;
  //check date is valid or not
  char dummy2[100]; //to copy date value
  strcpy(dummy2,attr[3]); // strcpy to copy a string to other
  char* date_token = strtok(dummy2,"-"); // tokenizing string
  char *date[3]; // to store 3 tokens
  i=0; 
  while (date_token != NULL)
  { 
    date[i++]=date_token; //assign token in array
    date_token = strtok(NULL,"-"); //further token the string
  }
  if(strlen(date[0])!=2)
    return 1;
  if(strlen(date[1])!=2)
    return 1;
  if(strlen(date[2])!=5)//since space is also counted in it 
    return 1;
  // converting string to int
  int dd,mm,yyyy;
  sscanf(date[0],"%d",&mm);
  sscanf(date[1],"%d",&dd);
  sscanf(date[2],"%d",&yyyy);
  //check if date is valid or not by calendar
  if(!isvaliddate(dd,mm,yyyy))
    return 1;
  return isvalid;
}

int main()
{
        char *fname="data.csv"; //change file name
  //printf("Enter file name: ");
  //scanf("%[^\n]%*c", fname);
  FILE *file;
        file = fopen(fname, "r");//open file in read mode
        int i = 0;
  char line[1024]; //store line
  int inv=0; //count invalid lines
        while (fgets(line, 1024, file))
  {
    if(strcmp(line,"END")==0)//if End appear break input stream
      break;
    else
    {
      if(!check_csv(line))// if valid print
        printf("%s",line);
      else
        inv++;
    }
  }
  printf("\nTotal no. of invalid lines are: %d\n",inv);
  return 0;
}

Input: CSV file

Output:


Related Solutions

Write a program that reads two strings from an input file (The first line is X,...
Write a program that reads two strings from an input file (The first line is X, the second line is Y), compute the longest common subsequence length AND the resulting string. You will need to write 2 methods 1) return LCS length in iterative function // return the length of LCS. L is the 2D matrix, X, Y are the input strings, m=|X|, n=|Y| int lcs_it(int **C, string X, string Y, int m, int n ) 2) return LCS resulting...
Write a program that reads and parses the CSV file, and can sort and filter data...
Write a program that reads and parses the CSV file, and can sort and filter data according to the user input and print the results. Your program should be able to do the following according to the user input: 1. Show results from a specific country 2. Sort the data according to any column 3. Filter the results (for example, >10000 cases) 4. Print the top or bottom n results You get bonus points if your program • Can do...
Python 8.17 LAB: Strings of a Frequency Write a program that reads whitespace delimited strings (words)...
Python 8.17 LAB: Strings of a Frequency Write a program that reads whitespace delimited strings (words) and an integer (freq). Then, the program outputs the strings from words that have a frequency equal to freq in a case insensitive manner. Your specific task is to write a function wordsOfFreqency(words, freq), which will return a list of strings (in the order in which they appear in the original list) that have a frequency same as the function parameter freq. The parameter...
In this programming assignment, you will write a program that reads in the CSV file (passenger-data-short.csv),...
In this programming assignment, you will write a program that reads in the CSV file (passenger-data-short.csv), which contains passenger counts for February 2019 on 200 international flights. The data set (attached below) is a modified CSV file on all International flight departing from US Airports between January and June 2019 reported by the US Department of Transportation. You write a program that give some summary statistics on this data set. Create a header file named flights.h. In this file, you...
JAVA PROGRAMMING RecallNoIF! Write a program named RecallNoIF that reads an integer representing a year. (In...
JAVA PROGRAMMING RecallNoIF! Write a program named RecallNoIF that reads an integer representing a year. (In this case there is no prompt from the program.) The program prints out RECALL if the year was 2004, 2010 or 2015 and NO RECALL otherwise. CONSTRAINT: Nowhere in the program is an if statement used. REMINDER: the program's output is shown here in bold; the user's data entry is shown here in italics. Sample Interactive Run 1: 2010 RECALL Sample Interactive Run 2:...
Write a program that reads three values from the keyboard representing, respectively, an investors name, an...
Write a program that reads three values from the keyboard representing, respectively, an investors name, an investment amount, and an interest rate (you will expect the user to enter a number such as .065 for the interest rate, representing a 6.5% interest rate) . Your program should calculate and output (in currency notation) the future value of the investment in 10, 2 20 an 30 years using the following formula:   Future value =investment(1+interest rate)year Example of a test run: Enter...
Write a program that reads three double numbers from the keyboard representing, respectively, the three coefficients...
Write a program that reads three double numbers from the keyboard representing, respectively, the three coefficients a, b, and c of a quadratic equation. Solve the equation using the following formulas: x1 = ( - b + square root (b2 – 4ac)) / (2a), x2 = ( - b + square root (b2 – 4ac)) / (2a) Run your program on the following sample values: a=1.0, b=3.0,c=2.0 a=0.5, b=0.5,c=0.125 a=1.0, b=3.0,c=10.0
Write a program read in data from the standard input stream (cin) representing temperature in Fahrenheit....
Write a program read in data from the standard input stream (cin) representing temperature in Fahrenheit. The program will then convert the values into Kelvin (using 5/9 (Fº-32) to convert to Celsius and a difference of 273.15 between Celsius and Kelvin) and print out the new total value. Convert temperature in Fahrenheit to Kelvin : Enter temperature in Fahrenheit: 80.33 The temperature in Kelvin is: 300 Write a second program which then does the reverse conversion (using a difference of...
I am trying to create a program that reads from a csv file and finds the...
I am trying to create a program that reads from a csv file and finds the sum of total volume in liters of liquor sold from the csv file by county and print that list out by county in descending order. Currently my program runs and gives me the right answers but it is not in descending order. I tried this:     for county, volume in sorted(sums_by_volume.items(), key=lambda x: x[1], reverse=True):         index +=1         print("{}. {} {:.2f}".format(county, sums_by_volume[county]))      When I run...
Write a program in c that reads the content from the file and stores each line...
Write a program in c that reads the content from the file and stores each line in an int array in heap(using dynamic memory allocation). For example, let the file has elements following (we do not know the size of files, it could be above 100,000 and contents of the file and make sure to convert file elements to int): 10067 26789 6789 3467
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT