C ++如何将字符串中的字符显示为数字

C++ How would I display characters in a string as a number

我正在为 class 开发一个回文程序。我已经编写了程序并且可以运行。我遇到的问题是输出。我不知道如何将字符更改为与之关联的数字。这是我的代码:

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

int main ()
{
    string word;
    int i;
    int length;
    int counter = 0;

    cout << "Please enter a word." << endl;
    getline (cin,word);

    cout << "The length of the word is " << word.length() << "." << endl;

    length = word.length();

    for (i=0;i < length ; i++)
    {
        cout << "Checking element " << word[i] << " with element " word[length-i-1] << "." << endl;

        if (word[i] != word[length-i-1])
        {
                counter = 1; 
                break;
        }

    }

    if (counter)
    {
         cout << "NO: it is not a palindrome." << endl;
    }
    else
    {
         cout << "YES: it is a palindrome." << endl;
    }
    return 0;
}

我得到的输出显示了字符串的所有字符,如下所示: my output

Please enter a word
hannah
Checking element h with element h
Checking element a with element a
Checking element n with element n

(等等)

Yes: it is a palindrome.

但是,我需要输出将字符显示为它们在字符串中的位置编号,如下所示:

what output should be

Please enter a word
hannah
Checking element 0 with element 5
Checking element 1 with element 4
Checking element 2 with element 3 
Yes: it is a palindrome.

任何提示或提示都会很棒。我只是觉得我已经尝试了我所知道的一切,但它看起来仍然不对。谢谢!

这一行:

cout << "Checking element " << word[i] << " with element " word[length-i-1] << "." << endl;

应该写成

cout << "Checking element " << i << " with element " << length-i-1 << "." << endl;

给你想要的。

而不是使用:

cout << "Checking element " << word[i] << " with element " word[length-i-1] << "." << endl;

为什么不使用:

cout << "Checking element " << i << " with element " << (length-i-1) << "." << endl;