【问题标题】:C++ How would I display characters in a string as a numberC ++如何将字符串中的字符显示为数字
【发布时间】:2018-02-19 03:37:35
【问题描述】:

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

#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.

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

【问题讨论】:

  • 我忘了补充一点,我只需要显示字符串中的一半字符。我试过:length-i-1

标签: c++ arrays string character palindrome


【解决方案1】:

而不是使用:

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

为什么不使用:

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

【讨论】:

    【解决方案2】:

    这一行:

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

    应该写成

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

    会给你你想要的。

    【讨论】:

    • @Isabella,如果答案有帮助别忘了给他们投票,如果他们解决了你的问题,别忘了选择一个答案作为你问题的解决方案。跨度>
    猜你喜欢
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    相关资源
    最近更新 更多