繁体   English   中英

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

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

我正在为班级编写回文程序。 我已经编写了程序并且它可以工作。 我遇到的问题是输出。 我不知道如何将字符更改为与之关联的数字。 这是我的代码:

#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

(等等)

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;

会给你你想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM