Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanning ASCII value of each character of a string

Tags:

c++

c

string

ascii

Is there anyway , if I enter any string , then I want to scan ASCII value of each character inside that string , if I enter "john" then I should get 4 variables getting ASCII value of each character, in C or C++

like image 721
Kamal Kafkaesque Avatar asked Jan 30 '26 16:01

Kamal Kafkaesque


1 Answers

Given a string in C:

char s[] = "john";

or in C++:

std::string s = "john";

s[0] gives the numeric value of the first character, s[1] the second an so on.

If your computer uses an ASCII representation of characters (which it does, unless it's something very unusual), then these values are the ASCII codes. You can display these values numerically:

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

Being an integer type (char), you can also assign these values to variables and perform arithmetic on them, if that's what you want.

I'm not quite sure what you mean by "scan". If you're asking how to iterate over the string to process each character in turn, then in C it's:

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

and in (modern) C++:

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

If you're asking how to read the string as a line of input from the terminal, then in C it's

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

and in C++ it's

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

If you mean something else by "scan", then please clarify.

like image 66
Mike Seymour Avatar answered Feb 02 '26 05:02

Mike Seymour



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!