Question: Programming C Reversing a String Objectives Practice taking program arguments Practice using C libraries and functions Practice converting strings to integers Practice manipulating C strings
Programming C
Reversing a String
Objectives
Practice taking program arguments
Practice using C libraries and functions
Practice converting strings to integers
Practice manipulating C strings
Practice top-down program design and reading pseudocode
Overview
For this lab, you will write a program that reads N lines of data from the terminal, one entire line at a time, and reverses the words of each line. In this example, N = 1:
$ ./lab6 1 the quick brown fox jumps over the lazy dog dog lazy the over jumps fox brown quick the
N is a number provided via a command-line argument--details below.
Details
Requirements:
Take in a single command-line argument--this is how many lines of input the user will enter.
Print an error message if not enough or too many program arguments
Convert this argument to an integer (print error and quit if user entered less than 0)
Do the following N times:
Get an entire line of user input using fgets and store it in array.
Using a function you implement yourself, reverse the words in the array.
The words must appear in reverse order, but still readable from left to right. (That is, the characters in each word are still in their original order.)
For example, "I pet the dog" becomes "dog the pet I"
The input strings will not have any puncuation, and will have exactly one space between each word.
Print out the reversed array
Command-line arguments
Command-line arguments are a way for you to provide input to the program at the moment it is executed. They follow the name of the program when you call it, for example:
$ ./myProgram someValue someOtherValue
This passes in "someValue" and "someOtherValue" to myProgram as command line arguments.
To access and use these command line arguments, we're going to change the declaration of our main method to the following:
int main( int argc, char **argv ) { ... } Here, argc is the number of arguments that were passed in, including the name of the program. So in our myProgram example, argc would be equal to 3 (the prgram name, "someValue" and "someOtherValue"). argv is an array of character pointers to our command line arguments: put another way, it's a 2D array of character arrays. Put another way, it's an array of strings, each representing a command line argument! The first string is the name of the program name; the rest are the arguments the user passed in. In our example, argv[0] is a character array containing "myProgram", argv[1] contains "someValue" and argv[2] contains "someOtherValue". Here's how we could print the first command line argument (not inluding the program name):
int main( int argc, char **argv[] ) { printf("%s", argv[1]); // Prints out "someValue" } So, if we are taking in a single value to represent the value of N, we could retrieve it via argv[1]. However, this will give us a character array, and we need an int.
Convert string to int
To obtain the value of N from this command-line argument, you must convert it to an int. Use the function strtol to accomplish this. With the call to strtol, you must provide the 'base' of the number returned. In our case, we want a standard 'base 10' number returned. In addition, you will need to use type casting to convert the result of the function back into an int.
int N = (int) strtol( str, NULL, 10);
NOTE: Be sure to #include
Standard Input using fgets
In this lab, you will use a function called fgets to read input from the keyboard. This function is also used to read data from files, however we can use it to read keyboard input by specifying the global variable stdin as the file pointer parameter. Up until now, we have typically used scanf to accomplish this, but fgets is actually better, because we can control how much data is read in. This helps to prevent buffer overflow errors, in which the string is stored in memory that is not allocated for it. To read input in this way, use the function like this:
#define SIZE 80 ... char str[SIZE]; if ( fgets( str, SIZE, stdin ) ) { // input was successful } The above fgets call places the first SIZE characters of user input (up until they hit return) into str. Because fgets returns a pointer to str if successful and a null (0) pointer if it wasn't, we can put it inside an if statement to see if it worked.
Algorithm to reverse words in a string (char array)
You may attempt to design an algorithm to solve this problem on your own if you'd like. However, you may also implement a C language version of the pseudocode provided below.
NOTE: The lines in red were updated on 4/2
PROCEDURE reverse( string line ): // temp is where we will concatenate the words in reverse order. Initialize it to an empty string. temp <- ""; idx <- string length of line - 2 word_len <- 0 // scan thru characters one by one loop until idx < 0: if line[ idx ] is a space and word_len > 0: Use strncat to copy word_len characters into temp. As the source, pass a pointer to line[idx + 1] Use strncat to append a space (" ") onto the end of temp. word_len <- 0 // reset word length to 0 else : // Line[idx] is alphanumeric word_len <- word_len + 1 end if // Decrement idx idx <- idx - 1 end loop // copy over the last word after the loop (if any) if word_len > 0: Use strncat to concatenate word_len characters onto the end of temp. (Pass a pointer to the first element of line as the source) end if Use strncpy to copy temp into line. Now line is a reverse of the original! end PROCEDURE Functions of interest (you may not need all of these)
stdio.h:
fgets
Read data from files or standard input
stdlib.h:
strtol
Convert a string to a long integer
ctype.h:
isalnum
Checks if a character is alphanumeric
string.h:
memset
Sets memory to a specific value. Useful to re-initialize local string variables to 0 for re-use in a loop.
strncpy
Copies some number of characters out of a string.
strlen
Gets the number of characters in a string (not including the null terminator).
strcat
Concatenates one string onto another.
strchr
Searches a string for the first occurrance of the given character
Example Execution
$ ./lab6 ERROR: Please provide an integer greater than or equal to 0 $ ./lab6 -3 ERROR: Please provide an integer greater than or equal to 0 $ ./lab6 2 the quick brown fox jumps over the lazy dog dog lazy the over jumps fox brown quick the what is love love is what $ ./lab6 1 a test... i demand a test! test a demand i test a
Compile & Test
Compile your program using this gcc command. c99 is a shortcut for running gcc -std=c99, which uses the C99 standard instead of the default C89 standard.
$ gcc -Wall -std=c99 lab6.c -o lab6
NOTE: Make sure you output closely matches the Example Execution.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
