This is the program that we were told to do where you take input of a string and reverse it and then output it.
Code Notes:
- I didn't use the "string.h" header since Engr. Mohammed did not teach it in class.
- The code I am posting works, but of course, due to compatiblity issues and plain old human error, things might go wrong. If
and whenthey do go wrong, post a comment below the relevant post or just contact me. - The day Engr.
TunjiOkewole taught us, he was supposed to take us some stuff on strings but he didn't. The slide I posted previously contains this information. Please endeavour to read it to the end. - I try to make my programs as efficient as possible, at times at the risk of simplicity; but I am not perfect, no one is. Please
I'm begging youfeel free to post suggestions for improvement. - Also, I will use functions as much as possible since that's what the lecturer encourages.
- Please don't get frustrated. Remember murphy's law: Anything that can go wrong will go wrong.
- I created two character arrays (character arrays are also known as strings). One for input (original text you type in) and for ouput (the reversed text).
- I used the "cin.getline" function to fill in the "input" character array with the string. Please check up on it.
- Next, an int variable "num" is intitialized for counting the number of characters typed into the program (including spaces).
- Then, the input and output arrays and also the num variable are passed into the function that does the real work (I use pointers to pass in num).
- In the function, I assign a value to num by using a while loop which increments the variable from 0, till the character '\0' (end of string) is encountered.
- And finally, I use a for loop to assign the last character of input to the first character of output, second-to-the-last to second of output, e.t.c.
- We then leave the "ReverseIt()" function
- And now, we have an output array with reversed letters, which is simply output using another for loop (back in the main() function).
And now, the code:
* Download the code: ReverseIt#include <iostream>void ReverseIt(char[], char[], int*);using namespace std;int main(){cout << "This is a program that receives input of a string and reverses it" << endl;char input[51] = {}, output[50] = {};int num = 0, counter = 0;char ans = 'y';while ((ans == 'y') || (ans == 'Y')){counter++;cout << "\nPlease enter the string: ";if (counter > 1)cin.get();cin.getline(input, 50, '\n');ReverseIt(input, output, &num);for (int i = 0; i <= num; i++)cout << output[i];cout << endl << "Would you like to do it again? (Y/N): "; cin >> ans;cout << endl << endl;}return 0;}void ReverseIt(char input[], char output[], int* Pnum){int n = 0;while (input[n] != '\0')n++;*Pnum = n;for (int i = 0; n >= 0; i++, n--)output[i] = input[n];}
* Remember, arrays and for loops are conjoined twins. They go together everywhere.
* Download: EEG 206 slide
No comments:
Post a Comment