C Program This program is a modification of one you did for lab 6 (shown below)
ID: 3595833 • Letter: C
Question
C Program
This program is a modification of one you did for lab 6 (shown below)
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
printf("Program name %s ", argv[0]);
FILE *f;
char ch;
int upper=0,lower=0;
if( argc == 2 )
{
printf("The argument supplied is %s ", argv[1]);
}
else
{
printf("One argument expected. ");
return 0;
}
f=fopen(argv[1],"r");
if ( f == 0 )
{
printf( "Could not open file " );
}
else
{
while((ch=getc(f))!=EOF)
{
if (ch >= 'A' && ch <= 'Z')
upper++;
if (ch >= 'a' && ch <= 'z')
lower++;
}
fclose(f);
printf(" Uppercase Letters : %d", upper);
printf(" Lowercase Letters : %d ", lower);
}
}
The program takes the name of an input file as its single command line argument and prints the number of upper-case letters, lower-case letters, and digits found in each worst. No word will ever be longer than 50 characters. A sample exuction is shown below, using the file DATA.
The file DATA contents:
AlAbAmA
Est. 1831
Crimson
Tide#1
./a.out DATA
AlAbAmA - 4 uppercase, 3 lowercase, 0 digits
Est. 1831 - 1 uppercase, 2 lowercase, 4 digits
Crimson - 1 uppercase, 6 lowercase, 0 digits
TIDE#1 - 4 uppercase, 0 lowercase, 1 digits
- Your program should confirm the input file exists (exit with an appropriate error message if it does not).
- You must use a function to count the number of uppercase, lowercase, and digits in a given word. The function must use the signature shown below.
void countCase(char*, int*, int*, int*);
This function passes a string and returns the number of uppercase letters, lowercase letters, and digits to the calling routine through the second, third, and fourth parameters.
Explanation / Answer
Please find my implementation.
#include <stdio.h>
#include <string.h>
void countCase(char*, int*, int*, int*);
int main( int argc, char *argv[] )
{
printf("Program name %s ", argv[0]);
FILE *f;
if( argc == 2 )
{
printf("The argument supplied is %s ", argv[1]);
}
else
{
printf("One argument expected. ");
return 0;
}
f=fopen(argv[1],"r");
if ( f == 0 )
{
printf( "Could not open file " );
}
else
{
int read;
char line[51];
int up = 0, lo = 0, di = 0;
while (fgets(line, sizeof(line), f)) {
up = 0;
lo = 0;
di = 0;
countCase(line, &up, &lo, &di);
printf("%s - %d uppercase, %d lowercase, %d digits ", line, up, lo, di);
}
fclose(f);
}
}
void countCase(char* str, int* up, int* lo, int* di) {
int len = strlen(str);
int i;
char ch;
for(i=0; i<len; i++) {
ch = str[i];
if (ch >= 'A' && ch <= 'Z')
(*up)++;
else if (ch >= 'a' && ch <= 'z')
(*lo)++;
else if (ch >= '0' && ch <= '9')
(*di)++;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.