No values of array are being printed out with cout in C++

Viewed 151

I have this piece of code that I want to write elements of an array with. However, nothing gets written on the standard output. When I try to return a value in an array everything is fine, and the for loop is also not the problem. Any ideas?

#include <iostream>
using namespace std;
int write(unsigned char* a, int n) {

    for (int i=0; i<n; i++) {
        std::cout << a[i] << '\n';
    }
    return -1;
}

int main() {
    int n;
    std::cin >> n;
    unsigned char* a = new unsigned char[n];
    for (int i=0; i<n; i++) {
        int x;
        std::cin >> x;
        a[i] = (unsigned char)x; 
    }

    std::cout << write(a,n) << '\n';
    delete[] a;
    return 0;
}
2 Answers

What integer values are you entering? I’m guessing they are very low (≤32). When you write an (unsigned) char value to a formatted output stream, the character value is written, not the numeric value. (And on most modern systems, low character values correspond to non-printable characters, so you won’t necessarily see any output.)

If you want to write numbers, you need to change your code to

for (int i = 0; i < n; i++) {
    std::cout << static_cast<int>(a[i]) << '\n';
}

Or:

std::copy_n(a, n, std::ostream_iterator<int>(std::cout, "\n");

I've tried the below input and it works.

3 a b c

The only change required is changing the int to char as your are working with char.

    for (int i=0; i<n; i++) {
        char x; //changed this line
        std::cin >> x;
        a[i] = (unsigned char)x; 
    }
Related