0
Help!
#include <iostream> using namespace std; int main() { string a; cin>>a; for(int y=a.length();y=0;y--){ for(int i=0;i<a.length();i++){ a[i]=a[y-1]; } } cout<<a return 0; } Why isn’t this code inversing the input string??
7 Réponses
+ 1
There is a problem with the logic. if you reverse string by its length , what will happen when both variables cross the middle? they will swap the swapped chars, no?
Example:
Start: [H][E][L][L][O]
v v
iter 1: [O][E][L][L][H]
v v
iter 2: [O][L][L][E][H]
vv
iter 3: [O][L][L][E][H]
v v
iter 4: [O][E][L][L][H]
v v
iter 5: [H][E][L][L][O]
i believe you must reverse up to middle (length / 2). you also need temporary variable to swap and not overwrite the characters.
i could do it your way except without nested loop, (but then you have to guard against division by 0) so i would do this instead:
size_t len = a.length();
for (size_t i = 0, end = len-1; i < len >> 1; i++) {
char swp = a[i];
a[i] = a[end - i];
a[end - i] = swp;
}
+ 1
What is this code suppose to do and what is the input you are giving?
+ 1
Nazeefa Labiba All you need to do is-
string a;
cin >> a;
for(int i=a.length()-1;i>=0;i--){
cout << a[i];
}
0
I am trying to make it inverse
0
I have tried to use >= in its place but still it is not working
0
plss help me