Comparing string content?

I'm expecting my if statement to comparing two strings but for a palindrome. If you type madam for example the if statement doesnt see its the same in reverse?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  //
//  prac.cpp
//  prac
//
//  Created by Joel on 29/11/2017.
//  Copyright © 2017 Joel. All rights reserved.
//

#include "prac.hpp"
#include <iostream>
#include <string>

using namespace std;

/** create a back up system */


int main()
{
    string input;
    string reversed;
    unsigned long getStringLen;
    bool isPalindrome;
    
    std::cout << " Enter some words: ";
    getline(cin, input);
    
    getStringLen = input.length();
    
    for( long i = getStringLen; i >= 0; i-- )
    {
        reversed += input[i];
    }
    
    cout << "reverse: " << reversed << endl;
    cout << "input: " << input << endl;
    
    if(input == reversed){
        cout << " we're the same!\n";
    }
        
    
    
    
    return 0;
}
arrays and string indices are indexed from 0 to length-1. You start your iteration at length instead of length-1.

change for loop to
1
2
3
4
    for( long i = getStringLen; i > 0; i-- )
    {
        reversed += input[i-1];
    }


PS: If you know about complexities (Big Oh notation), you should note that your implementation is O(n^2) time, where n is the string length. You can determine if a word is a palinddrome in O(n) time more efficiently. But this doesn't matter if you're just beginning.
Last edited on
I don't see why the -1 on the length is there?

Is it to compensate for the counting starting at 0?
Last edited on
Try going through it mentally on a short string, say "abc".
a is index 0
b is index 1
c is index 2

getStringLen = 3
so, i starts at 3, which means i-1 is 2, which is the index of c.
i is decremented to 2, and i-1 is 1, which is the index b.
l is decremented to 1, and i-1 is 0, which is the index of a.
i is decremented to 0, but now the for-loop condition is false, and looping ends.

For signed integer types, you could equivalently do
1
2
3
4
for (long i = getStringLen-1; i >= 0; i--)
{
    reversed += input[i];
}

but note that this would create an infinite loop for an unsigned type, such as size_t.
Last edited on
Topic archived. No new replies allowed.