asc and chr equivalent in C/C++
Asked Answered
B

3

5

Well the title pretty much sums it up. I want to use something like asc("0") in C++, and want to make the program platform independent so don't want to use 48! Any help appreciated.

Bass answered 19/6, 2011 at 21:8 Comment(1)
Don't forget to "accept" an answer that meets your needs!Iverson
U
10

You can simply use single-quotes to make a character constant:

char c = 'a';

The character type is a numeric type, so there is no real need for asc and chr equivalents.

Here's a small example that prints out the character values of a string:

#include <stdio.h>

int main(int argc, char **argv) {
  char str[] ="Hello, World!";

  printf("string = \"%s\"\n", str);

  printf("chars = ");
  for (int i=0; str[i] != 0; i++) 
    printf("%d ", str[i]);
  printf("\n");

  return 0;
}

The output is:

string = "Hello, World!"
chars = 72 101 108 108 111 44 32 87 111 114 108 100 33 
Unprejudiced answered 19/6, 2011 at 21:11 Comment(2)
oh right . absolutely! i dont know how i overlooked such a simple way, and i actually knew it all along, lol. thanks anyway!Bass
yeah i guess i need a reputation of 15 to vote up! as soon as i do, ill be back here to vote up !Bass
K
3

In C and C++, if you use a character enclosed by '' and not "" it means you are dealing with its raw binary value already.

Now, in C and C++, "0" is a literal two byte null-terminated string: '0' and '\0'. (ascii 48 ascii 0)

You can achieve what you want by using var[0] on a "" null-terminated string or use one of the conversion routines. (atoi() in C, stringstream lib in C++)

Kneeland answered 19/6, 2011 at 21:12 Comment(2)
Also, seeing that you are new to the site, don't forget to upvote the answers that you find useful and accepting the one that is the most useful for you. Welcome!Kneeland
i need a reputation of 15 to vote up! as soon as i do, ill be back here to vote up !Bass
H
0

You will get the ASCII value of a 0 character by writing: '0'.
Likewise 'char' for every char you need.

Hefty answered 19/6, 2011 at 21:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.