扫描字符串的每个字符的ASCII值

时间:2012-11-16 07:29:50

标签: c++ c string ascii

无论如何,如果我输入任何字符串,那么我想扫描该字符串中每个字符的ASCII值,如果我输入“john”那么我应该得到4个变量获得每个字符的ASCII值,在C或C ++中

5 个答案:

答案 0 :(得分:8)

给出C中的字符串:

char s[] = "john";

或在C ++中:

std::string s = "john";

s[0]给出第一个字符的数值,s[1]给出第二个字符的数值。

如果您的计算机使用ASCII字符表示(除非它是非常不寻常的),那么这些值就是ASCII码。您可以用数字显示这些值:

printf("%d", s[0]);                     // in C
std::cout << static_cast<int>(s[0]);    // in C++

作为整数类型(char),您还可以将这些值分配给变量并对它们执行算术运算,如果这是您想要的。

我不太清楚“扫描”是什么意思。如果您正在询问如何迭代字符串以依次处理每个字符,那么在C中它是:

for (char const * p = s; *p; ++p) {
    // Do something with the character value *p
}

和(现代)C ++:

for (char c : s) {
    // Do something with the character value c
}

如果你问如何从终端读取字符串作为一行输入,那么在C中它是

char s[SOME_SIZE_YOU_HOPE_IS_LARGE_ENOUGH];
fgets(s, sizeof s, stdin);

并且在C ++中它是

std::string s;
std::cin >> s;  // if you want a single word
std::getline(std::cin, s); // if you want a whole line

如果你的意思是“扫描”,那么请澄清。

答案 1 :(得分:2)

无法将长度为'x'的字符串转换为x变量。在C或C ++中,您只能声明固定数量的变量。但可能你不需要做你说的话。也许你只需要一个数组,或者你很可能只需要一个更好的方法来解决你想要解决的任何问题。如果你首先解释问题是什么,那么我肯定可以解释一个更好的方法。

答案 2 :(得分:2)

您可以通过将char转换为int:

来简单地获取char的ascii值
char c = 'b';
int i = c; //i contains ascii value of char 'b'

因此,在您的示例中,获取字符串的ascii值的代码如下所示:

#include <iostream>
#include <string>

using std::string;
using std::cout;
using std::endl;

int main()
{
    string text = "John";

    for (int i = 0; i < text.size(); i++)
    {
        cout << (int)text[i] << endl; //prints corresponding ascii values (one per line)
    }
}

要从表示ascii表中的条目的整数中获取相应的char,您只需将int再次转换回char:

char c = (char)74 // c contains 'J'

上面给出的代码是用C ++编写的,但它在C语言中的工作方式基本相同(我猜也是很多其他语言)

答案 3 :(得分:1)

Ya,I think there are some more better solutions are also available but this one also be helpful. In C

#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main(){
  char s[]="abc";
  int cnt=0;
  while(1){
    if(s[cnt++]==NULL)break;
  }
  int *a=(int *)malloc(sizeof(int)*cnt);
  for(int i=0;i<cnt;i++)a[i]=s[i];
  for(int i=0;i<cnt-1;i++)printf("%d\n",a[i]);  
  return 0;
}

In C++

#include <iostream>
#include <string>
using namespace std;
int main(){
    string s="abc";
    //int *a=new int[s.length()];
    //for(int i=0;i<s.length();i++)a[i]=s[i];
    for(int i=0;i<s.length();i++)
    cout<<(int)s[i]<<endl;
    return 0;
}

I hope this one will be helpful..

答案 4 :(得分:0)

是的,这很容易..只是一个演示

int main()
{
 char *s="hello";
 while(*s!='\0')
  {
  printf("%c --> %d\n",*s,*s);
  s++;
  }
 return 0;
}

但请确保您的计算机支持ASCII值格式。 在C中,每个char都有一个与之关联的整数值,称为ASCII。 使用%d格式说明符,您可以直接打印上述任何字符的ASCII。

注意:最好是自己获得好书并练习这种程序。