I have an exercise that says:
Codify a program that reads from the keyboard a keyword of up to 15 characters and a text of up to n lines (where n is a constant value). The program must eliminate from the text those lines that contain the keyword and print the “modified” text on the screen.
I have more or less an idea how to save the keyword and the text by lines.
This is the code I have:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 4 //Este es el nº máximo de líneas
int main()
{
int i;
char clave[15];
char linea[20];
char *texto[MAX]; //array dinámico para el texto
printf("Introduce la palabra clave\n");
gets(clave);
for(i=0; i<MAX; i++)
texto[i]=NULL; //Inicializo a NULL
printf("Texto original\n=============\n");
for(i=0; i<MAX; i++)
{
printf("Introduce la %dº linea:\n",i);
gets(linea);//leo las lineas del texto
if(strstr(linea,clave)==NULL)
{
texto[i]=(char*) malloc(strlen(linea)+1);//guardo bloque
strcpy(texto[i],linea);//le adjudico las lineas al texto
}
}
From here I am stuck, how do I compare the keyword and identify it in the lines of text to eliminate it, and print the modified text on the screen again?
You need to know which lines you are discarding and add to the array
texto
only the lines that do not contain the keyword.The first change I've made to your code is cosmetic:
I have modified
i
byi+1
so that you do not show the text in the output0º
.To solve your problem, I've defined the variable
j
, which I initialize to0
and increment every time I add a line to the arraytexto
.Later, inside the
if
one that compares if the key exists inside the entered line, I assign the reserved buffer to the line of textj
I copy the line entered in it
texto[j]
and increment the valuej
once the copying is done.At the end of the code, I print the array with the added lines:
CONSIDERATIONS
gets
is very dangerous, it is easy to get a Buffer Overflow, it should be changed tofgets(str, 19, stdin);
.texto
, which is not necessary.I put the complete code:
Well, you should compare each line with the key and with strstr check if it returns a value or not, if not, the line will not contain the key. I give you the example for a line:
More info