read_line function is as follows: int read_line(FILE *fp, char *str, int n) { in
ID: 3738452 • Letter: R
Question
read_line function is as follows:
int read_line(FILE *fp, char *str, int n)
{
int ch, i =0;
while ((ch = fgetc(fp)) != ' ')
{
// printf("%c", ch);
if (i < n)
*str++ = ch;
}
*str= '';
return i;
}
Explanation / Answer
This code will work for delimiters space and comma...
I'm giving you three functions main(), and your read_line(), and one split() function.
I have given the input directly as char *s = "TBH IDK if my has IRL something like CYA";
3 functions:
#include<stdio.h>
#include<sys/types.h>
#include<sys/file.h>
#include<unistd.h>
int read_line(FILE *fp, char *str, int n)
{
int ch, i =0;
while ((ch = fgetc(fp)) != ' ')
{
// printf("%c", ch);
if (i < n)
*str++ = ch;
}
*str= '';
return i;
}
int split (const char *str, char c, char ***arr)
{
int count = 1;
int token_len = 1;
int i = 0;
char *p;
char *t;
p = str;
while (*p != '')
{
if (*p == c)
count++;
p++;
}
*arr = (char**) malloc(sizeof(char*) * count);
if (*arr == NULL)
exit(1);
p = str;
while (*p != '')
{
if (*p == c)
{
(*arr)[i] = (char*) malloc( sizeof(char) * token_len );
if ((*arr)[i] == NULL)
exit(1);
token_len = 0;
i++;
}
p++;
token_len++;
}
(*arr)[i] = (char*) malloc( sizeof(char) * token_len );
if ((*arr)[i] == NULL)
exit(1);
i = 0;
p = str;
t = ((*arr)[i]);
while (*p != '')
{
if (*p != c && *p != '')
{
*t = *p;
t++;
}
else
{
*t = '';
i++;
t = ((*arr)[i]);
}
p++;
}
return count;
}
int main (int argc, char ** argv)
{
int i,j,k;
char *s = "TBH IDK if my has IRL orij oij CYA";
int c = 0;
char **arr = NULL;
c = split(s, ' ', &arr);
const char* acr[11]={"TBH","BRB","LOL","IDK","TTYL","IRL","TIA","AFK","CYA","FYI","OMG"};
for(i=0;i<11;i++)
{
for(j=0;j<c;j++)
{
if(strcmp(acr[i],arr[j])==0)
printf("%s ",arr[j]);
}
}
c = split(s, ',', &arr);
for(i=0;i<11;i++)
{
for(j=0;j<c;j++)
{
if(strcmp(acr[i],arr[j])==0)
printf("%s ",arr[j]);
}
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.