Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

ou need to write a C function named parse. The prototype is: int parse(char *);

ID: 3591899 • Letter: O

Question

ou need to write a C function named parse. The prototype is:

int parse(char *);

The function accepts a string; scans it with sscanf to try to convert it to
an integer; and returns a value as follows:

if the integer=1, return 1
if the integer=2, return 2
if the integer=3, return 3
in all other cases, return -1

This means if the string is empty, if it starts with a non-digit, if it's
an integer bigger than 3 or less than 1, if it has non-printabe characters,
etc. then your function should return -1. Use sscanf to do the conversion.
If sscanf can convert it to an integer, use that integer value and make sure
it's between 1 and 3. If sscanf can't convert it to an integer, return -1.

Write your own main test function to test your parse function.
Test it however you see fit: you can hardwire values, input values
while your program runs, use command line parameters, of whatever else
makes sense to you.

If your main function is called main.c compile as follows:

gcc -o main main.c parse.c

Test your program thoroughly. Then, once you are convinced that it works,
assess it as follows:

put your function in a file named parse.c
There should not be a main function in parse.c: it should only contain your function.

Explanation / Answer

//Please see the code below

1) parse.c

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

int parse(char *input)
{
   int data=-1;
   int ret=-1;
   //char c=*input;
   ret=sscanf(input, "%d", &data);

   if(ret==0 || data<1 || data>3)
       return -1;

   return data;
}

2) main.c

#include<stdio.h>

int parse(char *input)
int main()
{
   char text[10]="1";
   int returnValue=parse(text);
   printf("Return value is %d",returnValue);
   return 0;
}