user2210821
user2210821

Reputation: 21

printing ASCII codes of characters stored in C-string - explanation needed

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

Answers (3)

LihO
LihO

Reputation: 42083

while (*p1) 
    cout << (int) *p1++ << ' ';

means:

  • while p1 points to character value of which is different from 0 (i.e. '\0')
    • obtain the character it points to (*p1 = dereferencing of pointer p1)
    • cast this character to int so that ASCII code is outputted (number instead of character)
    • output space after the number that has been just printed
    • increment pointer p1 to make it point to the next character

Upvotes: 4

Caladan
Caladan

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

NPE
NPE

Reputation: 500317

cout << (int) *p1++ << ' ';

Here:

  1. The character pointed to by p1 is converted to an int and written to cout followed by a single space.
  2. p1 is advanced to point to the next character (this is what p1++ does).

Upvotes: 1

Related Questions