C 我将如何在字符串中显示字符作为数字

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

本文关键字:字符 显示 数字 字符串      更新时间:2023-10-16

我正在研究课堂的palindrome程序。我已经编写了该程序,它有效。我遇到的问题是输出。我不知道如何将字符更改为与之关联的数字。这是我的代码:

#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;
}

我将获得的输出显示字符串的所有字符,看起来像这样:我的输出

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

(etc(

Yes: it is a palindrome.

但是,我需要输出才能将字符显示为字符串中的位置号,看起来像这样:

哪些输出应为

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;

会给您想要的东西。