21xrx.com
2024-09-20 05:53:23 Friday
登录
文章检索 我的文章 写文章
C++如何输出字符串的ASCII码?
2023-07-13 07:49:38 深夜i     --     --
C++ 输出 字符串 ASCII码

在C++中,可以通过一些简单的语句来输出字符串的ASCII码。

第一种方法是使用for循环遍历字符串,在每个字符上调用int()函数转换为整型,然后输出其ASCII码。代码如下:


#include <iostream>

using namespace std;

int main() {

  string str = "Hello World";

  for(int i = 0; i < str.length(); i++) {

    cout << "ASCII code of " << str[i] << " is " << int(str[i]) << endl;

  }

  return 0;

}

输出结果如下:


ASCII code of H is 72

ASCII code of e is 101

ASCII code of l is 108

ASCII code of l is 108

ASCII code of o is 111

ASCII code of  is 32

ASCII code of W is 87

ASCII code of o is 111

ASCII code of r is 114

ASCII code of l is 108

ASCII code of d is 100

第二种方法是使用c_str()函数将字符串转换为字符数组,然后使用for循环遍历数组输出每个字符的ASCII码。代码如下:


#include <iostream>

using namespace std;

int main() {

  string str = "Hello World";

  const char *cstr = str.c_str();

  for(int i = 0; i < str.length(); i++) {

    cout << "ASCII code of " << cstr[i] << " is " << int(cstr[i]) << endl;

  }

  return 0;

}

输出结果与第一种方法相同。

通过这两种方法,可以很方便地输出字符串的ASCII码,这在一些需要处理字符的问题中很有用。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复