简体   繁体   中英

Char and Int in one Array

I want to have chars and ints inside one array. What i am trying to do is have 1 to 9 in my array and the user selects which number to replace with the letter X. How can i have this done? I assume i cant pass chars into an array that is called as int array[8]; So is there a way to have both ints and chars in an array?

In c++ int s and char s are almost the same thing. They are both stored as numbers, just with different resolutions.

int array[2];
array[0] = 100;
array[1] = 'c';

printf("%d", array[0]) //Prints the number at index zero.

//Is it %c to print a char?
printf("%c", array[1]) //Prints the number at index zero as it's equivalent char.

Why don't you just use an array of characters?

You can do

char characters[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', 0}; // last one is NULL terminator

int replace = 1;
cout << "Enter the number you want to replace with X: ";
cin >> replace;

assert(replace > 0 && replace < 10); // or otherwise check validity of input

characters[replace - 1] = 'X';

// print the string
cout << characters;

// if the user entered 5, it would print
// 1234X6789

A stab in the dark, because there is a large distinction between the user-model and the programming model.

When the user 'inserts' a character at a specified index, you want to update an array of char instead of inserting the value in your int array. Maintain the 2 side-by-side.

As others have mentioned, char will be promoted to int when you assign elements of the int[] array with char values. You would have to use an explicit cast when you are reading from that array.

Ie, the following works

int a[10];
char c='X';

a[0] = c;
c = (char) a[0];

HOWEVER,

Since you would need to keep track of which elements hold ints and which hold chars -- this is not an attractive solution.

Another option is just have an array of char and store the digits 0..9 as chars. Ie, '0','1', ..'9'.

(A third option is just have another variable store the index to the 'X' element -- but this is very different than what you are suggesting)

You can treat your numbers as characters

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


    //Assume you read it 
    int userInput = 9;
    mychar[userInput-1] = 'X';

The simplest solution is to use -1 instead of X assuming that your array does not have any negative numbers. I have done that before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM