Click here to Skip to main content
15,885,919 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello Guys..

Please, Help me out of this...! The sample code is like this..

C++
int i = 65;
char c = static_cast<char>(i);  // here c stores the letter 'A'.

In my Program, Every time i value changes & Am converting integer to char. But my doubt is How do i store char into character array ?

For Example: i values are 65,66,67 and so on.. & Am converting into equivalent characters like 'A','B','C' & so on.. And, I want to store these A,B,C characters into Character array..

Please suggest me some ideas..

Thanks..
Posted
Updated 13-Mar-12 21:20pm
v2
Comments
Sergey Alexandrovich Kryukov 14-Mar-12 2:30am    
Not clear what's the problem. Array or not, store whatever you want.
--SA

C++
#include <stdio.h>
int main()
{
    const int maxItems = 10;
    char myArray[maxItems], curChar;
    int i;
    for (i=0; i<maxItems; i++)
    {
        curChar = i;
        curChar += 'a';
        myArray[i] = curChar;
    }
    for (i=0; i<maxItems; i++)
    {
        printf("Item %d: '%c'\n", i, myArray[i]);
    }
    return 0;
}
 
Share this answer
 
v2
Comments
Guru_C++ 14-Mar-12 3:09am    
Woh...!! Cool.. It is working.. Thanks alot...
Guru_C++ 14-Mar-12 3:20am    
But how to avoid the Garbage value...! Am getting like this abcdefÌÌ
Stefan_Lang 14-Mar-12 5:10am    
You are probably looking at the variable myArray with some tool, maybe a debuggers inspection or watch window, or just some local variables view that your IDE provides. If that is the case, this tool will automatically try to interpret any variable of type 'array of char' as a C-style string. Unfortunately, this does not work here: a C-style string is defined as a series of characters terminated by a '0'.

The array myArray does not have that terminating 0, so your tool keeps interpreting the memory past the last character as part of the string, and since that memory contains random values, what you see is ASCII characters that correspond to these random values (which usually do look like garbage, as you said)
Not Clear,
But few instruction:
1. You do not need casting if you want use numeric data to set character value
e.g.
C++
//all of them are valid statement
char c;
c=65;
c=0x41; 
c='A';
c='A'+32; // you will get 'a'
c='A';
c++;      //you will get 'B'


2. To understand you need you need to learn about array. It is beyond scope here.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900