|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/correct/h6p01.c
/*
p01.c - (x pts)
You are going to loop through what was entered via command-line argument and print
out the longest word entered.
Remember, the number of arguments you enter on the command line is stored in the
integer variable argc, and the arguments entered are stored in the array of strings argv.
Use strlen to get the length of each string stored in argv
Look at cmdargs.c in the jun29 directory for an example where we just print each command
line argument on it's own line. Here, you're just going to print the longest of the arguments.
*/
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]){
//we do not need an usage statement code in this program
int len, longest = 0, longIndex = 0; //declaring variables
//use a for loop to loop through each argument
for(int i = 0; i < argc; i++){
len = strlen(argv[i]); //get the length of the string stored at argv[i]
if(len > longest){ //if the length of that string is longer than what's stored at longest
longIndex = i; //make whatever number i currently is the new longestIndex.
longest = len; //make whatever the len is the new longest
}
}
printf("The longest argument was %s\n", argv[longIndex]);
return 0;
}
|