c++ – Where I want to output a space in C ++, the number 32 is output instead

Question: Question:

Incomplete, but I wrote the code

#include<iostream>
#include <cstdlib>

using namespace std;

int main(int argc, char** argv)
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        for(int j=0;j<2*(n-1)+1;j++){
            cout<<(((j+1)<(i-1))?' ':(((n+i)>j)?' ':int(i+1)))<<endl;
        }
        cout<<endl;
    }
    return 0;
}

When executed,

3 //入力した値
32
32
32
1
1

32
32
32
32
2

32
32
32
32
32

Enterキーを押すと、ターミナルが終了します...

In the plan, the number will be a triangle from top to bottom from 1 to the entered value, but for some reason, the number 32 is displayed. I don't want to know the answer because it's an issue, but does anyone know why the number 32 is displayed?

Answer: Answer:

Perhaps the behavior of the ternary operator A ? B : C is misunderstood.

The ternary operator A ? B : C returns a value, but the type of the value must always be the same. In other words, the types of B and C must be the same. If not, the compiler checks if one type can be converted to the other, performs a type conversion if possible, and returns an error if not.

In this case, A ? (char型の値) : (int型の値) , so char ( ' ' ) with a small number of bits is converted to int . in short

  • char ' ' (character code 32) is
  • Converted to int
  • become int 32
  • Output with cout

It is a flow.

Scroll to Top