Reputation: 21
This program converts the char to their ASCII code
Program works perfectly, but i don't understand how the line cout << (int) *p1++ << ' ';
works. Еspecially *p1++
in this inner while
loop:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
void main ()
{
char s[80];
char *p1;
do
{
p1 = s;
cout << "Enter the string";
gets(p1);
while (*p1)
cout << (int) *p1++ << ' ';
cout << '\n';
}
while (strcmp (s, "End"));
}
Upvotes: 2
Views: 1278
Reputation: 42083
while (*p1)
cout << (int) *p1++ << ' ';
means:
p1
points to character value of which is different from 0 (i.e. '\0'
)
*p1
= dereferencing of pointer p1
)int
so that ASCII code is outputted (number instead of character)p1
to make it point to the next characterUpvotes: 4
Reputation: 1491
It's quite easy :)
while (*p1) => as long as the byte pointed by p1 is not zero.... cout << (int) *p1++ << ' '; => print char pointed by p1 and increment the pointer afterwards. Cast the result (char) into int and print it.
while (*p) {do_somthing(); p++;} is a common way of iterating through a c string.
Upvotes: 0
Reputation: 500317
cout << (int) *p1++ << ' ';
Here:
p1
is converted to an int
and written to cout
followed by a single space.p1
is advanced to point to the next character (this is what p1++
does).Upvotes: 1