C 我将如何在字符串中显示字符作为数字
C++ How would I display characters in a string as a number
我正在研究课堂的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;
会给您想要的东西。
相关文章:
- 字符串-C++后显示的随机字符
- 显示基于用户输入的整数的字符
- 在将字符插入 2d 字符串时如何不显示空字符?
- 为什么strlen(s)与s的大小不同,为什么cout-char显示的是字符而不是数字
- 为什么C++在将浮点数转换为字符时没有显示缩小转换错误?
- 链表显示垃圾字符
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 程序,它接受用户输入的字符并按出现的降序显示它们
- 使用带有诅咒库的 stdscr 创建窗口,在边框而不是线条中显示不需要的笑脸字符
- 如何检查输入是否为字符并显示它是"invalid input",否则它将按原样运行
- 如何在不将其转换为 ASCII 字符的情况下显示 QByteArray 的十六进制值
- 如何从显示板将字符显示为字符串?
- 将终端设置为原始模式:仅在按下下一个键后显示字符
- 在QLineEdit中显示和编辑转义字符
- 我的程序没有将字符显示在屏幕上
- C++控制台字符显示
- C++特殊字符显示为"?"
- 将字符显示为没有显式强制转换的整数
- 为什么sizeof为一个字符显示4个字节
- 使用'uxxxx'格式定义的字符显示错误的字符