Originally Posted by
vart
also it is a good practice to put with the array - the array length as a second parameter
in this case your printStrings function does not need to know that arrays are declared with STRING_COUNT constant
also when fgets returns null it could be not due to error but due to EOF condition, so maybe user just does not want to enter all 5 srings and will stop after 3 (he can emulate EOF pressing Ctrl+Z if I remember)
so in this case you also may want to proceed the actual number of received strings, and not the preallocated number - so passing the number of filled array members will also help to solve this problem
hi!
these are very important considerations so I tried to put them together in this other small program which shows and counts the strings which terminate by a key string entered by the user.
The problem is that i cannot catch the EOF condition properly (this is the reason why i entered the blank line request): if i press CTRL+Z i get just a "stopped" message and the program gets terminated... so the while cicle in my readlines() never fails (and i have to check in the block for blank lines!)
do you have any hints? is it possible to declare the key string in a more elegant way than the way i did? thanks again!
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINES 5
#define MAX_STRLEN 256
int readlines (char * lines[], int maxlines);
int countlines (char * lines[], int numlines, char * key,int keyDim);
void writelines (char * lines[],int numlines);
int main()
{
char *lines[MAXLINES], *key[1];
printf("Insert text. Leave a blank line when you're finished\n");
fflush(stdout);
int numl;
if ((numl=readlines(lines,MAXLINES))<0)
{
exit(1);
}
printf("Enter your key string\n");
fflush(stdout);
if (readlines(key,1)<0)
{
exit(1);
}
printf("Your entered lines (%d total):\n",numl);
writelines(lines,numl);
printf("Your key:\n");
writelines(key,1);
printf("String(s) which terminate by your key:\n");
printf("I found %d such line(s)\n",countlines (lines,numl,key[0],strlen(key[0])));
}
int readlines (char * lines[],int maxlines)
{
char buffer[MAX_STRLEN];
int line=1;
while ( fgets(buffer,MAX_STRLEN,stdin) )
{
if (strlen(buffer)==1) return line-1;
buffer[strlen(buffer)-1]='\0';
if (! (lines[line-1]=malloc(strlen(buffer)+1)) )
{
printf("Out of memory\n");
return -1;
}
strcpy(lines[line-1],buffer);
if (line==maxlines) return line;
line++;
}
return line-1;
}
int countlines (char * lines[], int numlines, char * key,int keyDim)
{
int i,count=0;
for(i=0;i<numlines;i++)
{
if ( strstr((lines[i]+(strlen(lines[i])-keyDim)),key) ) {
count++;
puts(lines[i]);
}
}
return count;
}
void writelines (char * lines[],int numlines)
{
int i;
for (i=0;i<numlines;i++)
{
puts(lines[i]);
}
}