Searching a simple pattern in input of the command line argument and reprint to the standard output

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Searching a simple pattern in input of the command line argument and reprint to the standard output

To show: Showing how to use the main() function and its command line arguments

 

#include <stdio.h>

 

// maximum input line length

#define MAXLINE 100

 

// function prototypes...

int getline(char line[], int max);

int strindex(char source[], char searchfor[]);

 

// pattern to be searched for in the line change accordingly

char pattern[] = "eat";

 

// find/display all line matching pattern

int main(void)

{

char line[MAXLINE];

int found = 0;

printf("Searching \'eat\' in the line of text\n");

printf("Enter line of text:\n");

while(getline(line, MAXLINE) > 0)

if(strindex(line, pattern) >= 0)

{ printf("%s", line);

found++;

}

return found;

}

 

// getline(), get line into string str, return the length

int getline(char str[], int lim)

{

int count, i;

i=0;

while(--lim > 0 && (count=getchar()) != EOF && count != '\n')

str[i++] = count;

if(count=='\n')

str[i++] = count;

str[i]='\0';

return i;

}

 

// strindex, return index of t in str, -1 if none

int strindex(char str[], char t[])

{

int i, j, k;

for(i=0;str[i]!='\0';i++)

{

for(j=i, k=0; t[k] != '\0' && str[j] == t[k]; j++, k++)

;

if(k > 0 && t[k] == '\0')

return i;

}

return -1;

}

 

Output example:

 

Searching 'eat' in the line of text

Enter line of text:

This is a line of text

eat something

eat something

There is an eat word in this line

There is an eat word in this line

If no eat word in the line, no output to the standard output

If no eat word in the line, no output to the standard output

No e.a.t word in this line?

Well this line will not print

Here the 'eat' word

Here the 'eat' word

^Z

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index