How can I get an array or string to output everything in it?

THERE IS MORE TO THIS QUESTION THEN IN THE THE TITLE.
I have an array that has some numbers and some letters. If I cout it with
1
2
for(random=0;random<myArray.size();random++)
    cout << int(myArray[random]);

it just couts the numbers and the ASCII value for the letters. If I cout it with
1
2
for(random=0;random<myArray.size();random++)
    cout << myArray[random];

it just outputs the letters and blanks for the numbers. How can I get it to display both the letters and the numbers?

EDIT- I have tried setting myArray to a stirng, a vector<string>, a vector <int>, and a vector<char>
Last edited on
What does the rest of the program look like? Because I've never seen myArray.size() used in this context before. Usually people declare a global integer called MAXVALUES or something along those lines and use that number.

EDIT:
Here is an example:
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;

int main()
{
    int myArray[5] = {5, 2, 8, 2541, 58};
    
    for(int i = 0; i < 5; i++)
    cout << myArray[i] << "\n";
}
Last edited on
IT doesn't matter what you use, I have used myArray.size() like this before and it has worked fine
I'm assuming you're using an std::vector, as raw arrays don't have a size member.

The problem is you probably aren't surrounding the numbers you input with ' ', so they get interpreted as ASCII codes.
> I have an array that has some numbers and some letters.

An array has either all letters or all numbers.

1
2
3
4
5
6
char c = 'a' ;
int i = c ;
double d = c ;
int array[] = { c /* initialized with an int (char widened to an int) */,
                 i /* initialized with an int */,
                 int(d)  /* initialized with an int (double narrowed to an int) */} ;

Every object in array[] is an object of type int.

In the absence of a discriminant, the best one can do is:
if the number in the array happens to be the numeric value of a char, print it as a char.
Something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <cctype>
#include <iostream>

bool is_printable_char( int n )
{
    return n >= std::numeric_limits<char>::min() &&
            n <= std::numeric_limits<char>::max() &&
            std::isprint(n) ;
}

void do_print( const int array[], int array_size )
{
    for( int i = 0 ; i < array_size ; ++i )
    {
        if( is_printable_char( array[i] ) )
            std::cout << "'" << char( array[i] ) << "' " ; // print it out as a char

        else // print it out as an int
            std::cout << array[i] << ' ' ;
    }
    std::cout << '\n' ;
}
Topic archived. No new replies allowed.