DrOnline DrOnline - 1 month ago 7
C++ Question

Inserting characters at specified position

I want to make a program that when the user enters

AB1245
and have the program change it to
AB 12345
(an added space between 2nd and 3rd character)

char Bilnr[9];

for (i = 8; i < 3; i--) {
Bilnr[i++]=Bilnr[i];

}


As I understand this, this program will start with Bilnr[9] and set it to the value of Bilnr[8].

Then set Bilnr[8] to the value of Bilnr[7].

But it doesn't move any of the values. It simply prints
AB1245
.

Answer

One thing I notice is that if your loop ever actually executes, it would be infinite

for (I=8; I<3; I--) {
    Bilnr[I++]=Bilnr[I];

}

I++ doesn't mean I+1 rather, it means I = I+1

but your loop won't execute, because your condition, I<3 will be false from the get-go when you initialize I with I=8

You're also never setting I[2] to be a ' '

you also also have to realize that arrays start at 0, so Bilnr[0] == 'A'

try

for(int i = 8; i > 2; i--)
{
    Bilnr[i] = Bilnr[i-1];
}
Bilnr[2] = ' ';