patriques
patriques

Reputation: 5211

How to save an int value in a char

I have integers under the value of 255 and want to save them into an char array. Im experimenting with some tests:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

int
main(void)
{
    char string[10];
    int integers[10]; //all under 255.

    int j;
    for(j=0; j<10; j++)
    {
            integers[j]=j;
    }

    int i;
    for(i=0; i<10; i++)
    {
            string[i]=(char)integers[i];
    }

    printf("%s \n", string);
    return 0;
}

when I run the debugger to the end of the of the program the string contains the following ascii values:

"\000\001\002\003\004\005\006\a\b\t"

First I dont understand why after the 006 an \a appears and at the end a \t?

Secondly I wonder if there is a better way to do what I am intending? Thanks

Upvotes: 0

Views: 2899

Answers (5)

Lundin
Lundin

Reputation: 214495

#include <stdio.h>

int main (void)
{
    char string[10];
    int i;

    for(i=0; i<10; i++)
    {
      string[i] = i;
    }
    string[9] = '\0';

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

    return 0;
}

Upvotes: 1

nayab
nayab

Reputation: 2380

use atoi function to convert ascii values to integer

Upvotes: 0

Dancrumb
Dancrumb

Reputation: 27549

What you're seeing are escaped representations of ASCII characters 0x06, 0x07, 0x08 and 0x09.

0x06 is ACK.

0x07 is BEL or \a (alert) and simply causes the terminal to go 'ding!'

0x08 is BS or backspace or \b.

0x09 is TAB or \t.

Upvotes: 6

Asdine
Asdine

Reputation: 3046

You don't need to create the first integer array. You can fill directly the string array.

char string[11];
int i;
for(i=0; i<10; i++)
{
    string[i] = i;
}
string[i] = '\0';

Upvotes: 0

Grhm
Grhm

Reputation: 6854

The ASCII characters you're using 0-9 are non-printable characters.

The printf function is formatting them as \nnn so that they can be seen.

The ASCII character 9 is a tab character, commonly represented as \t
The ASCII character 8 is the backspace character, represented as \b
The ASCII character 7 is a bell "or alarm" character, common represented as \a

See http://web.cs.mun.ca/~michael/c/ascii-table.html

Upvotes: 2

Related Questions