0
Will some one explain to me, line by line, exactly how this code works?
#include<iostream> #include<string.h> using namespace std; int main () { char str[50], temp; int i, j; cout << "Enter a string : "; gets(str); j = strlen(str) - 1; for (i = 0; i < j; i++,j--) { temp = str[i]; str[i] = str[j]; str[j] = temp; } cout << "\nReverse string : " << str; return 0; } // I'm having trouble understanding the algorithm and even harder time applying it. Thanks in advance. //
3 ответов
+ 2
Tanner Crane take an examples string I take as example "Hi"
Now gets() will read it and store in buffer reader and variable "str" so now in str there is string "Hi"
In next line strlen(str) will calculate the length of str which is 2 and 2-1 will store 1 in J.
Now for loop will execute till the value J so for loop will execute one time. For that value of i=0 and j=1
Then swap logic is written inside for loop which is works as below
Str is "Hi"
Temp = str[0] so Temp = "H"
str[0] = str[1] means at string str index one character which is "i" is assign to str[0] index 0.
So str[0]= "i"
Then str[1] = Temp which is "H"
So str[1] = "H"
Now print the string which is str[0]+str[1] = iH
So input string is Hi and output string is iH
So this way the code works
+ 2
Additional notes to our good friends' explanations
Avoid using `gets` at all cost. `gets` is not considered a safe way to reading user input because it doesn't care about buffer size. If you write more than the amount the buffer can hold, you're getting yourself into trouble.
If your code was in C, use `fgets` or `scanf`to read user input.
If your code was in C++, use `cin >> buffer;` for reading input without any whitespace. Or use `getline(cin, buffer);` for reading input with whitespaces. Assuming <buffer> is your string variable name.
Header string.h is included as #include <cstring> in C++, file extension '.h' is not needed except if you are including custom headers. e.g. your own header file, or headers that are part of non standard library.
* Recent discussion on `gets` function topic
https://www.sololearn.com/Discuss/2108381/?ref=app
+ 1
Inside the "for" loop there is the swap of two characters, in positions i and j (we must use a temp storage to not overwrite one of the two characters).
"i" is initialized as the first index of the string (0), "j" is initialized as the last index of the string: strlen()-1
So first loop swaps first and last characters, second loop exchange second character with near to last and so one. The loops terminate when the first increasing half index (i) becomes equal or bigger than the second6 decreasing half index (j)